liveBook · Manning

Terraform import

As explained in Infrastructure as Code, Patterns and Practices: With examples in Python and Terraform

terraform import is a Terraform command that associates an existing infrastructure resource with a Terraform state.

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

How Infrastructure as Code, Patterns and Practices: With examples in Python and Terraform covers it

How deep it goes
Explains provider lookup, dynamic identifiers, batch automation, validation, and subsequent state removal, but does not detail import syntax.
Examples
Uses GCP service accounts, project IAM role assignments, Python automation, an alreadyExists error, and a no-change Terraform plan.
What it assumes
Assumes Terraform configuration and provider access, while demonstrating provider API retrieval and state-management steps.
What you can do after
Operate/configure Terraform-managed resources after importing live infrastructure and verifying that planned changes are absent.
How it connects
Connects Terraform state with infrastructure provider APIs, infrastructure as code, IAM policies, and configuration refactoring.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Infrastructure as Code, Patterns and Practices: With examples in Python and Terraform. The section links point to the parts of the book it draws on.