Overview and What You Will Learn
Terraform import brings a resource that already exists in your cloud account under Terraform management by recording it in state, so you can manage it as code without recreating it. It is how a team that built an AWS account by clicking in the console adopts infrastructure as code without downtime. Import only writes state, so you also need a matching resource block, and your job is to edit that block until terraform plan reports no changes.
By the end of this lab you will be able to:
- Import resources with declarative
importblocks, which are reviewable in a pull request - Find the correct import ID for common AWS resources
- Fix plan differences until the imported resource shows no changes
- Generate a first draft of the configuration with
-generate-config-out - Import several resources at once and import into modules
- Use the older
terraform importcommand safely when you need it - Handle attributes that cannot be imported, such as database passwords
Why This Matters in Production
Destroying and recreating live systems is not an option. Imagine a platform team at a company like PhonePe that inherits hundreds of hand-built resources serving live payment traffic. They adopt Terraform one service at a time, starting with the least critical, and for each one they write the configuration, import it, and fix the plan until it is clean. Once a service is managed, a new environment becomes an apply of existing code instead of days of manual work.
Core Principles
Import connects three things: the real resource, a resource block in your code, and an entry in state. The goal is a clean plan, which proves your code describes the resource as it really is.
RememberImport does not write your configuration unless you ask Terraform to generate it. If the code does not match the real resource, the next apply changes the live resource to match your code.
Detailed Step-by-Step Practical Lab
What Should You Do Before You Import?
Prepare so a mistake is easy to undo.
- Use a remote backend with locking, so state is shared and protected
- Back up current state with
terraform state pull > backup.tfstate - Use credentials for the right account and region
- Start with a low-risk resource in a non-production account if you can
How to Import a Resource with an Import Block
An import block names the Terraform address and the real resource ID. Terraform shows the import in the plan, so reviewers see exactly what will be adopted before it happens. This is the recommended method on Terraform 1.5 and later.
resource "aws_instance" "payments_api" { ami = "ami-0f5ee92e2d63afc18" # copy the real values from the console instance_type = "t3.large"} # imports.tfimport { to = aws_instance.payments_api id = "i-0a1b2c3d4e5f6789"}terraform plan# aws_instance.payments_api will be imported# Plan: 1 to import, 0 to add, 1 to change, 0 to destroy. terraform applyThe plan also lists the differences between your draft and the real instance, which is the work you do next.
How to Find the Right Import ID
The import ID differs by resource type, and the provider documentation for each resource lists it under an Import section. These are common AWS cases:
| Resource | Import ID | Example |
|---|---|---|
| EC2 instance | Instance ID | i-0a1b2c3d4e5f6789 |
| S3 bucket | Bucket name | phonepe-customer-data-prod |
| Security group | Group ID | sg-0a1b2c3d4e5f6789a |
| RDS instance | DB identifier | phonepe-payments-postgres-prod |
| IAM role | Role name | phonepe-payments-api-role |
# EC2 instance by Name tagaws ec2 describe-instances \ --filters "Name=tag:Name,Values=phonepe-payments-api-prod" \ --query "Reservations[].Instances[].InstanceId" --output text # RDS instance by exact identifieraws rds describe-db-instances \ --db-instance-identifier phonepe-payments-postgres-prod \ --query "DBInstances[0].DBInstanceIdentifier" --output text # Security group by nameaws ec2 describe-security-groups \ --filters "Name=group-name,Values=phonepe-payments-api-sg" \ --query "SecurityGroups[0].GroupId" --output textHow to Fix Plan Differences After Import
A draft block will rarely match on the first try. Use the plan as a checklist, and use terraform state show to see every attribute Terraform read from the real resource.
terraform state show aws_instance.payments_apiterraform plan ~ aws_instance.payments_api will be updated in-place ~ ebs_optimized = false -> true ~ monitoring = false -> true ~ iam_instance_profile = null -> "phonepe-payments-api-profile" ~ metadata_options { ~ http_tokens = "optional" -> "required" }Each ~ line means your code says one thing and reality says another. Edit the code to match reality:
resource "aws_instance" "payments_api" { ami = "ami-0f5ee92e2d63afc18" instance_type = "t3.large" ebs_optimized = true monitoring = true iam_instance_profile = "phonepe-payments-api-profile" metadata_options { http_endpoint = "enabled" http_tokens = "required" http_put_response_hop_limit = 1 } tags = { Name = "phonepe-payments-api-prod" Environment = "prod" }}Repeat plan and edit until the plan reports no changes. Do not apply while the plan still shows changes you did not intend.
terraform plan# No changes. Your infrastructure matches the configuration.Common MistakeApplying right after import without reading the plan. If your block is incomplete, apply turns off settings such as monitoring or IMDSv2 on a live production resource.
How to Generate the Configuration Automatically
If writing drafts by hand is slow, let Terraform generate them. Write import blocks without matching resource blocks, then ask plan to write the configuration to a new file. The output file must not already exist.
# imports.tfimport { to = aws_instance.payments_api id = "i-0a1b2c3d4e5f6789"}terraform plan -generate-config-out=generated.tfTreat the generated file as a first draft. It lists many attributes, including computed ones, and sometimes contains combinations the provider rejects. Review it, remove attributes you do not want to manage, move the cleaned block into your real files, then run plan until it is clean.
How to Import Many Resources or Import into Modules
Use for_each in an import block, available from Terraform 1.7, to import a set of similar resources. Target a resource inside a module by including the module path in to.
locals { buckets = { assets = "phonepe-assets-prod" customers = "phonepe-customer-data-prod" }} import { for_each = local.buckets to = aws_s3_bucket.managed[each.key] id = each.value} resource "aws_s3_bucket" "managed" { for_each = local.buckets bucket = each.value} # Import into a resource inside a moduleimport { to = module.network.aws_vpc.main id = "vpc-0a1b2c3d4e5f6789a"}How to Import S3 Sub-Resources
In the AWS provider, a bucket's settings are separate resources, and each needs its own import. For these resources the ID is the bucket name.
import { to = aws_s3_bucket.customer_data id = "phonepe-customer-data-prod"} import { to = aws_s3_bucket_public_access_block.customer_data id = "phonepe-customer-data-prod"} import { to = aws_s3_bucket_versioning.customer_data id = "phonepe-customer-data-prod"} import { to = aws_s3_bucket_server_side_encryption_configuration.customer_data id = "phonepe-customer-data-prod"}When Should You Use the terraform import Command?
The command terraform import ADDRESS ID imports one resource immediately and writes to state at once, with no plan and no review. It is useful for a quick one-off or on Terraform versions before 1.5. The resource block must already exist.
terraform state pull > backup.tfstate # always back up firstterraform import aws_instance.payments_api i-0a1b2c3d4e5f6789For team work, prefer import blocks, because the import is visible in a pull request before it runs.
What Should You Do After a Successful Import?
Once the plan is clean and applied, the import blocks have done their job. Terraform ignores an import block for a resource that is already in state, so leaving it is harmless, but most teams remove them to keep the code tidy. Commit the final resource blocks, then run a fresh plan in CI to confirm it stays clean.
terraform state list # confirm the resource is trackedterraform plan -detailed-exitcode # exit 0 means no changesHow to Handle Attributes That Cannot Be Imported
Some arguments are write-only or secret and are never read back, such as an initial database password. After import, the plan may want to set them.
resource "aws_db_instance" "main" { identifier = "phonepe-payments-postgres-prod" engine = "postgres" instance_class = "db.r6g.large" allocated_storage = 500 username = "payments_admin" # The existing password cannot be read back. Let AWS manage it going forward manage_master_user_password = true deletion_protection = true}If you must keep the current password, use lifecycle { ignore_changes = [password] } and rotate it outside Terraform.
Production Best Practices & Common Pitfalls
- Import one service at a time. Get one service's plan clean, commit, and apply before moving on. Each step stays small and reviewable.
- Prefer import blocks over the CLI command. They appear in the plan, can be reviewed in a pull request, and are repeatable across environments.
- Expect several plan and edit rounds. A clean plan is the goal, not a perfect first draft.
- Back up state before importing.
terraform state pull > backup.tfstatecosts nothing and makes mistakes reversible. - Never import the same object into two addresses or two states. Two Terraform configurations managing one resource will fight each other.
- Apply only when the plan shows exactly what you expect. Import is safe, but applying a mismatched config changes live resources.
- Lock down state afterwards. Imported state holds the real attributes of production resources, so keep it in an encrypted remote backend.
SecurityImported state can contain sensitive attributes in plaintext. Use an encrypted remote backend with restricted access before importing production resources.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
terraform plan |
Shows Plan: N to import for import blocks |
terraform plan -generate-config-out=generated.tf |
Drafts resource blocks from import blocks |
terraform state show ADDRESS |
Lists every attribute Terraform read |
terraform state list |
Confirms which resources are tracked |
terraform state pull > backup.tfstate |
Backs up current state |
terraform import ADDRESS ID |
Imports one resource immediately |
| Error | Root Cause | Fix |
|---|---|---|
| Resource already managed by Terraform | It is already in state | Check terraform state list |
| Cannot import non-existent remote object | Wrong ID, region, or account | Verify with the AWS CLI |
| Resource type does not support import | Provider limitation | Check the provider documentation |
Plan shows -/+ after import |
An argument in your code forces replacement | Read the forces-replacement note and match the real value |
| Generated file already exists | -generate-config-out needs a new file |
Choose a new filename or delete the old one |
| Generated config fails validation | Provider rejects some computed attributes | Remove the conflicting attributes and re-plan |