terraform import associates existing infrastructure resources with Terraform state, allowing separated configuration to manage live resources without recreating them. A practical trigger is refactoring IAM resources out of a monolithic configuration: applying the new configuration first can fail because the service account already exists. section 10.2.1
A safe import workflow:
- Retrieve current resource state and identifiers from the infrastructure provider API. section 10.2.1
- Search API results using tags and naming conventions rather than assuming identifiers remain unchanged. section 10.2.1
- Import the existing resources into the separated Terraform state, optionally wrapping Terraform in Python for batch operations. section 10.2.1
- Run a plan or dry run and confirm that Terraform reports no changes before removing the resources from the monolith’s state and configuration. section 10.2.1
Separating IAM resources
A separated GCP IAM configuration initially attempts to create an existing service account and receives an alreadyExists error. Importing the current service accounts and role assignments, followed by terraform plan, produces “No changes” and avoids disruption. section 10.2.1
Figure 10.7 Get the current state of the separated resources from the infrastructure provider and import the identifiers before reapplying IaC.
Shows the migration sequence: obtain current provider state, import resource identifiers, and reapply infrastructure as code. section 10.2.1
