Import resources that already exist
In this task you'll bring resources that already exist under Terraform.
Import blocks (Terraform 1.5 and later) tell Terraform to adopt an existing resource by its Azure ID. terraform plan -generate-config-out=generated.tf writes matching configuration for you to review.
Success is a plan with only imports and no changes: anything else means the code doesn't match yet.
Example. SS Kaiser's hand-built shop network was imported in an afternoon: four import blocks, generated config, a clean plan and an apply that changed nothing.
Before you start
You need: A Terraform stack. Time: 30 minutes.
Where to look
- imports.tf
- terraform plan -generate-config-out
- terraform apply
Steps
- Get each resource's ID with
az <service> show --query id -o tsv. - Write import blocks only, then
terraform plan -generate-config-out=generated.tf. - Review generated.tf: it often needs tidying. In our test the network came out with flow_timeout_in_minutes = 0 and an empty inline subnet list, which the provider rejects.Delete or fix such lines; a subnet managed as its own resource shouldn't also appear inside the network.
- Plan until it says N to import, 0 to add, change or destroy, then apply.
- Plan again: No changes.
Commands
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
terraform plan -generate-config-out=generated.tf
terraform apply
terraform state list
Watch out for
- Cost
- Free.
- Security
- Generated code may include values you'd rather not keep in Git (keys, connection strings): review it.
- Common mistakes
- Missing child resources (such as a subnet's NSG association), so the next plan wants to change them.
Clean up
terraform state rm stops managing a resource without deleting it.
Words to know
- Import block
- to = resource address, id = Azure resource ID.
- generate-config-out
- Writes resource blocks for imported resources.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On