Table of Contents

Why Import Existing Infrastructure?

When you have resources created manually (via console or CLI) that you want Terraform to manage going forward, you need to import them into Terraform state.

Method 1: terraform import (Classic)

Step 1: Write the Resource Configuration

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  # Add all attributes that match the existing resource
}

Step 2: Run the Import Command

terraform import aws_instance.web i-1234567890abcdef0

Step 3: Verify with Plan

terraform plan
# Should show no changes if configuration matches reality

Step 4: Adjust Configuration

If terraform plan shows differences, update your .tf files to match the imported resource.

Method 2: import Block (Terraform 1.5+)

The modern approach — declarative imports in configuration:

import {
  to = aws_instance.web
  id = "i-1234567890abcdef0"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
}

Then run:

terraform plan -generate-config-out=generated.tf  # Auto-generate config
terraform apply  # Execute the import

Common Import IDs by Resource

ResourceImport ID Format
aws_instanceInstance ID: i-1234567890abcdef0
aws_s3_bucketBucket name: my-bucket
aws_iam_roleRole name: my-role
aws_vpcVPC ID: vpc-abc123
aws_security_groupSG ID: sg-abc123
aws_db_instanceDB identifier: my-database
aws_lambda_functionFunction name: my-function

Best Practices

  1. Import one resource at a time — easier to debug
  2. Run plan after each import — verify configuration matches
  3. Use terraform state show to see all imported attributes
  4. Consider using terraformer for bulk imports
  5. Document what was imported — leave comments in code

Learn More