Import Existing Resources
Import is the routine that brings a resource Terraform did not create under Terraform control. The resource keeps running while its record moves into state.
Step 1: create a bucket outside Terraform
Make the bucket with the AWS CLI against the emulator. Terraform knows nothing about it yet.
aws --endpoint-url http://localhost:5000 s3api create-bucket --bucket my-old-bucket --region us-east-1Step 2: import it
The import command links the live bucket to a name in the config. The bucket itself is untouched.
terraform import aws_s3_bucket.legacy my-old-bucketStep 3: write matching config
Write a resource block that describes the bucket as it already is. The name must match the import.
resource "aws_s3_bucket" "legacy" {
bucket = "my-old-bucket"
}Steps 4 and 5: plan, then apply
Plan is the check. No changes means the config matches the live bucket.
terraform plan
terraform apply -auto-approveExample
# Start the emulator first: moto_server -p 5000
# Create the bucket outside Terraform:
# aws --endpoint-url http://localhost:5000 s3api create-bucket --bucket my-old-bucket --region us-east-1
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "us-east-1"
s3_use_path_style = true
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
s3 = "http://localhost:5000"
sts = "http://localhost:5000"
}
}
resource "aws_s3_bucket" "legacy" {
bucket = "my-old-bucket"
}
# terraform init
# terraform import aws_s3_bucket.legacy my-old-bucket
# terraform plan
# terraform apply -auto-approve
# terraform destroy -auto-approveKey points
- Some resources already exist before Terraform arrives.
- Import records a live resource in state without recreating it.
- The routine has five steps: identify, import, write matching config, plan, apply.
- The config must match the live resource, or plan will propose changes.
- A clean plan shows no changes after a good import.
- The bucket here is a mock one, made in the emulator on this machine.
The bucket was made outside Terraform, then imported into state. The matching config means plan finds nothing to change. The final destroy empties the mock cloud again.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does terraform import do to the live resource?