Import Azure Infrastructure into Terraform

Import Azure Infrastructure into Terraform

Guides an agent to discover existing Azure resources with the Azure CLI and turn them into Terraform code built on Azure Verified Modules, with correct import addresses.

Skill files1 file
SKILL.md368 lines
1
---
2
name: import-infrastructure-as-code
3
description: 'Import existing Azure resources into Terraform using Azure CLI discovery and Azure Verified Modules (AVM). Use when asked to reverse-engineer live Azure infrastructure, generate Infrastructure as Code from existing subscriptions/resource groups/resource IDs, map dependencies, derive exact import addresses from downloaded module source, prevent configuration drift, and produce AVM-based Terraform files ready for validation and planning across any Azure resource type.'
4
---
5
6
# Import Infrastructure as Code (Azure -> Terraform with AVM)
7
8
Convert existing Azure infrastructure into maintainable Terraform code using discovery data and Azure Verified Modules.
9
10
## When to Use This Skill
11
12
Use this skill when the user asks to:
13
14
- Import existing Azure resources into Terraform
15
- Generate IaC from live Azure environments
16
- Handle any Azure resource type supported by AVM (and document justified non-AVM fallbacks)
17
- Recreate infrastructure from a subscription or resource group
18
- Map dependencies between discovered Azure resources
19
- Use AVM modules instead of handwritten `azurerm_*` resources
20
21
## Prerequisites
22
23
- Azure CLI installed and authenticated (`az login`)
24
- Access to the target subscription or resource group
25
- Terraform CLI installed
26
- Network access to Terraform Registry and AVM index sources
27
28
## Inputs
29
30
| Parameter | Required | Default | Description |
31
|---|---|---|---|
32
| `subscription-id` | No | Active CLI context | Azure subscription used for subscription-scope discovery and context setting |
33
| `resource-group-name` | No | None | Azure resource group used for resource-group-scope discovery |
34
| `resource-id` | No | None | One or more Azure ARM resource IDs used for specific-resource-scope discovery |
35
36
At least one of `subscription-id`, `resource-group-name`, or `resource-id` is required.
37
38
## Step-by-Step Workflows
39
40
### 1) Collect Required Scope (Mandatory)
41
42
Request one of these scopes before running discovery commands:
43
44
- Subscription scope: `<subscription-id>`
45
- Resource group scope: `<resource-group-name>`
46
- Specific resources scope: one or more `<resource-id>` values
47
48
Scope handling rules:
49
50
- Treat Azure ARM resource IDs (for example `/subscriptions/.../providers/...`) as cloud resource identifiers, not local file system paths.
51
- Use resource IDs only with Azure CLI `--ids` arguments (for example `az resource show --ids <resource-id>`).
52
- Never pass resource IDs to file-reading commands (`cat`, `ls`, `read_file`, glob searches) unless the user explicitly says they are local file paths.
53
- If the user already provided one valid scope, do not ask for additional scope inputs unless required by a failing command.
54
- Do not ask follow-up questions that can be answered from already-provided scope values.
55
56
If scope is missing, ask for it explicitly and stop.
57
58
### 2) Authenticate and Set Context
59
60
Run only the commands required for the selected scope.
61
62
For subscription scope:
63
64
```bash
65
az login
66
az account set --subscription <subscription-id>
67
az account show --query "{subscriptionId:id, name:name, tenantId:tenantId}" -o json
68
```
69
70
Expected output: JSON object with `subscriptionId`, `name`, and `tenantId`.
71
72
For resource group or specific resource scope, `az login` is still required but `az account set` is optional if the active context is already correct.
73
74
When using specific resource scope, prefer direct `--ids`-based commands first and avoid extra discovery prompts for subscription or resource group unless needed for a concrete command.
75
76
### 3) Run Discovery Commands
77
78
Discover resources using the selected scopes. Ensure to fetch all necessary information for accurate Terraform generation.
79
80
```bash
81
# Subscription scope
82
az resource list --subscription <subscription-id> -o json
83
84
# Resource group scope
85
az resource list --resource-group <resource-group-name> -o json
86
87
# Specific resource scope
88
az resource show --ids <resource-id-1> <resource-id-2> ... -o json
89
```
90
91
Expected output: JSON object or array containing Azure resource metadata (`id`, `type`, `name`, `location`, `tags`, `properties`).
92
93
### 4) Resolve Dependencies Before Code Generation
94
95
Parse exported JSON and map:
96
97
- Parent-child relationships (for example: NIC -> Subnet -> VNet)
98
- Cross-resource references in `properties`
99
- Ordering for Terraform creation
100
101
IMPORTANT: Generate the following documentation and save it to a docs folder in the root of the project.
102
- `exported-resources.json` with all discovered resources and their metadata, including dependencies and references.
103
- `EXPORTED-ARCHITECTURE.MD` file with a human-readable architecture overview based on the discovered resources and their relationships.
104
105
### 5) Select Azure Verified Modules (Required)
106
107
Use the latest AVM version for each resource type.
108
109
### Terraform Registry
110
111
- Search for "avm" + resource name
112
- Filter by "Partner" tag to find official AVM modules
113
- Example: Search "avm storage account" → filter by Partner
114
115
### Official AVM Index
116
117
> **Note:** The following links always point to the latest version of the CSV files on the main branch. As intended, this means the files may change over time. If you require a point-in-time version, consider using a specific release tag in the URL.
118
119
- **Terraform Resource Modules**: `https://raw.githubusercontent.com/Azure/Azure-Verified-Modules/refs/heads/main/docs/static/module-indexes/TerraformResourceModules.csv`
120
- **Terraform Pattern Modules**: `https://raw.githubusercontent.com/Azure/Azure-Verified-Modules/refs/heads/main/docs/static/module-indexes/TerraformPatternModules.csv`
121
- **Terraform Utility Modules**: `https://raw.githubusercontent.com/Azure/Azure-Verified-Modules/refs/heads/main/docs/static/module-indexes/TerraformUtilityModules.csv`
122
123
### Individual Module information
124
125
Use the `web` tool or another suitable MCP method to get module information if not available locally in the `.terraform` folder.
126
127
Use AVM sources:
128
129
- Registry: `https://registry.terraform.io/modules/Azure/<module>/azurerm/latest`
130
- GitHub: `https://github.com/Azure/terraform-azurerm-avm-res-<service>-<resource>`
131
132
Prefer AVM modules over handwritten `azurerm_*` resources when an AVM module exists.
133
134
When fetching module information from GitHub repositories, the README.md file in the root of the repository typically contains all detailed information about the module, for example: https://raw.githubusercontent.com/Azure/terraform-azurerm-avm-res-<service>-<resource>/refs/heads/main/README.md
135
136
### 5a) Read the Module README Before Writing Any Code (Mandatory)
137
138
**This step is not optional.** Before writing a single line of HCL for a module, fetch and
139
read the full README for that module. Do not rely on knowledge of the raw `azurerm` provider
140
or prior experience with other AVM modules.
141
142
For each selected AVM module, fetch its README:
143
144
```text
145
https://raw.githubusercontent.com/Azure/terraform-azurerm-avm-res-<service>-<resource>/refs/heads/main/README.md
146
```
147
148
Or if the module is already downloaded after `terraform init`:
149
150
```bash
151
cat .terraform/modules/<module_key>/README.md
152
```
153
154
From the README, extract and record **before writing code**:
155
156
1. **Required Inputs** — every input the module requires. Any child resource listed here
157
(NICs, extensions, subnets, public IPs) is managed **inside** the module. Do **not**
158
create standalone module blocks for those resources.
159
2. **Optional Inputs** — the exact Terraform variable names and their declared `type`.
160
Do not assume they match the raw `azurerm` provider argument names or block shapes.
161
3. **Usage examples** — check what resource group identifier is used (`parent_id` vs
162
`resource_group_name`), how child resources are expressed (inline map vs separate module),
163
and what syntax each input expects.
164
165
#### Apply module rules as patterns, not assumptions
166
167
Use the lessons below as examples of the *type* of mismatch that often causes imports to fail.
168
Do not assume these exact names apply to every AVM module. Always verify each selected module's
169
README and `variables.tf`.
170
171
**`avm-res-compute-virtualmachine` (any version)**
172
173
- `network_interfaces` is a **Required Input**. NICs are owned by the VM module. Never
174
create standalone `avm-res-network-networkinterface` modules alongside a VM module —
175
define every NIC inline under `network_interfaces`.
176
- TrustedLaunch is expressed through the top-level booleans `secure_boot_enabled = true`
177
and `vtpm_enabled = true`. The `security_type` argument exists only under `os_disk` for
178
Confidential VM disk encryption and must not be used for TrustedLaunch.
179
- `boot_diagnostics` is a `bool`, not an object. Use `boot_diagnostics = true`; use the
180
separate `boot_diagnostics_storage_account_uri` variable if a storage URI is needed.
181
- Extensions are managed inside the module via the `extensions` map. Do not create
182
standalone extension resources.
183
184
**`avm-res-network-virtualnetwork` (any version)**
185
186
- This module is backed by the AzAPI provider, not `azurerm`. Use `parent_id` (the full
187
resource group resource ID string) to specify the resource group, not `resource_group_name`.
188
- Every example in the README shows `parent_id`; none show `resource_group_name`.
189
190
Generalized takeaway for all AVM modules:
191
192
- Determine child resource ownership from **Required Inputs** before creating sibling modules.
193
- Determine accepted variable names and types from **Optional Inputs** and `variables.tf`.
194
- Determine identifier style and input shape from README usage examples.
195
- Do not infer argument names from raw `azurerm_*` resources.
196
197
### 6) Generate Terraform Files
198
199
### Before Writing Import Blocks — Inspect Module Source (Mandatory)
200
201
After `terraform init` downloads the modules, inspect each module's source files to determine
202
the exact Terraform resource addresses before writing any `import {}` blocks. Never write
203
import addresses from memory.
204
205
#### Step A — Identify the provider and resource label
206
207
```bash
208
grep "^resource" .terraform/modules/<module_key>/main*.tf
209
```
210
211
This reveals whether the module uses `azurerm_*` or `azapi_resource` labels. For example,
212
`avm-res-network-virtualnetwork` exposes `azapi_resource "vnet"`, not
213
`azurerm_virtual_network "this"`.
214
215
#### Step B — Identify child modules and nested paths
216
217
```bash
218
grep "^module" .terraform/modules/<module_key>/main*.tf
219
```
220
221
If child resources are managed in a sub-module (subnets, extensions, etc.), the import
222
address must include every intermediate module label:
223
224
```text
225
module.<root_module_key>.module.<child_module_key>["<map_key>"].<resource_type>.<label>[<index>]
226
```
227
228
#### Step C — Check for `count` vs `for_each`
229
230
```bash
231
grep -n "count\|for_each" .terraform/modules/<module_key>/main*.tf
232
```
233
234
Any resource using `count` requires an index in the import address. When `count = 1` (e.g.,
235
conditional Linux vs Windows selection), the address must end with `[0]`. Resources using
236
`for_each` use string keys, not numeric indexes.
237
238
#### Known import address patterns (examples from lessons learned)
239
240
These are examples only. Use them as templates for reasoning, then derive the exact addresses
241
from the downloaded source code for the modules in your current import.
242
243
| Resource | Correct import `to` address pattern |
244
|---|---|
245
| AzAPI-backed VNet | `module.<vnet_key>.azapi_resource.vnet` |
246
| Subnet (nested, count-based) | `module.<vnet_key>.module.subnet["<subnet_name>"].azapi_resource.subnet[0]` |
247
| Linux VM (count-based) | `module.<vm_key>.azurerm_linux_virtual_machine.this[0]` |
248
| VM NIC | `module.<vm_key>.azurerm_network_interface.virtualmachine_network_interfaces["<nic_key>"]` |
249
| VM extension (default deploy_sequence=5) | `module.<vm_key>.module.extension["<ext_name>"].azurerm_virtual_machine_extension.this` |
250
| VM extension (deploy_sequence=1–4) | `module.<vm_key>.module.extension_<n>["<ext_name>"].azurerm_virtual_machine_extension.this` |
251
| NSG-NIC association | `module.<vm_key>.azurerm_network_interface_security_group_association.this["<nic_key>-<nsg_key>"]` |
252
253
Produce:
254
255
- `providers.tf` with `azurerm` provider and required version constraints
256
- `main.tf` with AVM module blocks and explicit dependencies
257
- `variables.tf` for environment-specific values
258
- `outputs.tf` for key IDs and endpoints
259
- `terraform.tfvars.example` with placeholder values
260
261
### Diff Live Properties Against Module Defaults (Mandatory)
262
263
After writing the initial configuration, compare every non-zero property of each discovered
264
live resource against the default value declared in the corresponding AVM module's
265
`variables.tf`. Any property where the live value differs from the module default must be
266
set explicitly in the Terraform configuration.
267
268
Pay particular attention to the following property categories, which are common sources
269
of silent configuration drift:
270
271
- **Timeout values** (e.g., Public IP `idle_timeout_in_minutes` defaults to `4`; live
272
deployments often use `30`)
273
- **Network policy flags** (e.g., subnet `private_endpoint_network_policies` defaults to
274
`"Enabled"`; existing subnets often have `"Disabled"`)
275
- **SKU and allocation** (e.g., Public IP `sku`, `allocation_method`)
276
- **Availability zones** (e.g., VM zone, Public IP zone)
277
- **Redundancy and replication** settings on storage and database resources
278
279
Retrieve full live properties with explicit `az` commands, for example:
280
281
```bash
282
az network public-ip show --ids <resource_id> --query "{idleTimeout:idleTimeoutInMinutes, sku:sku.name, zones:zones}" -o json
283
az network vnet subnet show --ids <resource_id> --query "{privateEndpointPolicies:privateEndpointNetworkPolicies, delegation:delegations}" -o json
284
```
285
286
Do not rely solely on `az resource list` output, which may omit nested or computed properties.
287
288
Pin module versions explicitly:
289
290
```hcl
291
module "example" {
292
source = "Azure/<module>/azurerm"
293
version = "<latest-compatible-version>"
294
}
295
```
296
297
### 7) Validate Generated Code
298
299
Run:
300
301
```bash
302
terraform init
303
terraform fmt -recursive
304
terraform validate
305
terraform plan
306
```
307
308
Expected output: no syntax errors, no validation errors, and a plan that matches discovered infrastructure intent.
309
310
## Troubleshooting
311
312
| Problem | Likely Cause | Action |
313
|---|---|---|
314
| `az` command fails with authorization errors | Wrong tenant/subscription or missing RBAC role | Re-run `az login`, verify subscription context, confirm required permissions |
315
| Discovery output is empty | Incorrect scope or no resources in scope | Re-check scope input and run scoped list/show command again |
316
| No AVM module found for a resource type | Resource type not yet covered by AVM | Use native `azurerm_*` resource for that type and document the gap |
317
| `terraform validate` fails | Missing variables or unresolved dependencies | Add required variables and explicit dependencies, then re-run validation |
318
| Unknown argument or variable not found in module | AVM variable name differs from `azurerm` provider argument name | Read the module README `variables.tf` or Optional Inputs section for the correct name |
319
| Import block fails — resource not found at address | Wrong provider label (`azurerm_` vs `azapi_`), missing sub-module path, or missing `[0]` index | Run `grep "^resource" .terraform/modules/<key>/main*.tf` and `grep "^module"` to find exact address |
320
| `terraform plan` shows unexpected `~ update` on imported resource | Live value differs from AVM module default | Fetch live property with `az <resource> show`, compare to module default, add explicit value |
321
| Child-resource module gives "provider configuration not present" | Child resources declared as standalone modules even though parent module owns them | Check Required Inputs in README, remove incorrect standalone modules, and model child resources using the parent module's documented input structure |
322
| Nested child resource import fails with "resource not found" | Missing intermediate module path, wrong map key, or missing index | Inspect module blocks and `count`/`for_each` in source; build full nested import address including all module segments and required key/index |
323
| Tool tries to read ARM resource ID as file path or asks repeated scope questions | Resource ID not treated as `--ids` input, or agent did not trust already-provided scope | Treat ARM IDs strictly as cloud identifiers, use `az ... --ids ...`, and stop re-prompting once one valid scope is present |
324
325
## Response Contract
326
327
When returning results, provide:
328
329
1. Scope used (subscription, resource group, or resource IDs)
330
2. Discovery files created
331
3. Resource types detected
332
4. AVM modules selected with versions
333
5. Terraform files generated or updated
334
6. Validation command results
335
7. Open gaps requiring user input (if any)
336
337
## Execution Rules for the Agent
338
339
- Do not continue if scope is missing.
340
- Do not claim successful import without listing discovered files and validation output.
341
- Do not skip dependency mapping before generating Terraform.
342
- Prefer AVM modules first; justify each non-AVM fallback explicitly.
343
- **Read the README for every AVM module before writing code.** Required Inputs identify
344
which child resources the module owns. Optional Inputs document exact variable names and
345
types. Usage examples show provider-specific conventions (`parent_id` vs
346
`resource_group_name`). Skipping the README is the single most common cause of
347
code errors in AVM-based imports.
348
- **Never assume NIC, extension, or public IP resources are standalone.** For
349
any AVM module, treat child resources as parent-owned unless the README explicitly indicates
350
a separate module is required. Check Required Inputs before creating sibling modules.
351
- **Never write import addresses from memory.** After `terraform init`, grep the downloaded
352
module source to discover the actual provider (`azurerm` vs `azapi`), resource labels,
353
sub-module nesting, and `count` vs `for_each` usage before writing any `import {}` block.
354
- **Never treat ARM resource IDs as file paths.** Resource IDs belong in Azure CLI `--ids`
355
arguments and API queries, not file IO tools. Only read local files when a real workspace
356
path is provided.
357
- **Minimize prompts when scope is already known.** If subscription, resource group, or
358
specific resource IDs are already provided, proceed with commands directly and only ask a
359
follow-up when a command fails due to missing required context.
360
- **Do not declare the import complete until `terraform plan` shows 0 destroys and 0
361
unwanted changes.** Telemetry `+ create` resources are acceptable. Any `~ update` or
362
`- destroy` on real infrastructure resources must be resolved.
363
364
## References
365
366
- [Azure Verified Modules index (Terraform)](https://github.com/Azure/Azure-Verified-Modules/tree/main/docs/static/module-indexes)
367
- [Terraform AVM Registry namespace](https://registry.terraform.io/namespaces/Azure)
368

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…