Bring Existing Infrastructure Under Terraform Control
terraform import lets you adopt manually created resources into Terraform without recreating them.
What
terraform import lets you bring manually created or existing resources under Terraform management without recreating them. You write the resource block in your configuration first, then run the import command to map the real resource into your Terraform state. From that point on, Terraform manages it.
Why It Matters
Most organizations have infrastructure that was created manually through the console or by other tools before adopting Terraform. Without import, you would have to destroy and recreate these resources to bring them under Terraform control, causing downtime and data loss for things like databases and S3 buckets.
Example
# Step 1: Write the resource block in your config
resource "aws_s3_bucket" "existing" {
bucket = "my-existing-bucket-name"
}
# Step 2: Import the real resource into state
terraform import aws_s3_bucket.existing my-existing-bucket-name
# Step 3: Run plan to see what config is missing
terraform plan
# The plan will show drift between your config and reality
# Add missing attributes until plan shows no changes
# Step 4: Verify with state show
terraform state show aws_s3_bucket.existing
# Terraform 1.5+ also supports import blocks in config:
import {
to = aws_s3_bucket.existing
id = "my-existing-bucket-name"
}Common Mistake
Importing a resource without writing the complete resource configuration first. After import, terraform plan will show unwanted changes or attempt to modify the resource because your config does not match reality.
Quick Fix
After importing, immediately run terraform plan and iteratively add missing attributes to your resource block until the plan shows no changes. Use terraform state show to see all the attributes Terraform knows about and match them in your config.
Key Takeaways
- 1terraform import maps existing resources into state
- 2Write the resource block FIRST, then import
- 3Run terraform plan after import to find missing config
- 4Iterate until plan shows zero changes
- 5Terraform 1.5+ supports import blocks in HCL
Was this tip helpful?
Help us improve the DevOpsPath daily collection