Tech Talk

Terraform – Import Azure Resources Into the State

Terraform – Import Azure Resources Into the State
  • Christoph Thale

  • 8 min

  • August 26, 2023

Someone created an Azure resource manually – and now Terraform wants to recreate it. Here's how terraform import works and how to handle modules, for_each loops, and CI/CD pipelines.

How to Bring Manually Created Azure Resources Under Terraform Control

When a manually created resource already exists in Azure but isn't in the Terraform state, a terraform apply will fail. The solution: import the resource into the state first.

The Basic Import Command

terraform import ADDRESS ID
  • ADDRESS – the path to the resource block in Terraform code (e.g. azurerm_storage_account.myexample)
  • ID – the Azure resource identifier (found in the portal or in error messages)

Finding the ID

The provider usually returns the ID in error messages. Alternatively, deploy an identical resource with a different name to learn the ID syntax, then construct the correct ID.

Importing From Modules and for_each Loops

For resources inside a module and a for_each loop, the ADDRESS includes both the module path and the key:

module.createStorageAccounts.azurerm_storage_account.fortheblog["key_of_stacc01"]

 

Scaling to Many Resources

For migrations involving hundreds of resources, collect all import commands in a shell script (importstatements.sh) and execute it in the CI/CD pipeline before terraform apply:


chmod +x ./importstatements.sh; ./importstatements.sh

Important: remove the shell script invocation from the pipeline once the import is complete.