terraform import: Bring Existing Resources Under Terraform Management
Step-by-step guide to terraform import. Import existing AWS, Azure, and GCP resources into Terraform state. Includes import blocks (Terraform 1.5+)
Terraform
Complete Terraform commands reference. Learn terraform init, plan, apply, destroy, state, import, output, workspace, fmt, validate
terraform init # Download providers and initialize
terraform fmt # Format code
terraform validate # Check syntax
terraform plan # Preview changes
terraform apply # Apply changes
terraform destroy # Destroy everything
terraform output # Show outputs
terraform state list # List managed resources
terraform import # Import existing resources
terraform console # Interactive expression evaluatorEvery Terraform project follows the same pattern:
terraform init → terraform plan → terraform applyInitialize the working directory. Downloads providers, sets up backend, installs modules:
terraform initCommon flags:
terraform init -upgrade # Upgrade providers to latest allowed version
terraform init -reconfigure # Reconfigure backend without migration
terraform init -migrate-state # Migrate state to new backend
terraform init -backend=false # Skip backend configurationRun init when:
Preview what Terraform will do — without changing anything:
terraform plan # aws_instance.web will be created
+ resource "aws_instance" "web" {
+ ami = "ami-0c55b159cbfafe1f0"
+ instance_type = "t3.micro"
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.Useful flags:
terraform plan -out=plan.tfplan # Save plan to file
terraform plan -target=aws_instance.web # Plan one resource only
terraform plan -var="region=eu-west-1" # Override a variable
terraform plan -destroy # Preview what destroy would do
terraform plan -refresh=false # Skip state refresh (faster)Apply the changes:
terraform apply # Interactive (asks for confirmation)
terraform apply -auto-approve # Skip confirmation (CI/CD)
terraform apply plan.tfplan # Apply a saved plan
terraform apply -target=aws_instance.web # Apply one resource
terraform apply -replace="aws_instance.web" # Force-recreate a resource
terraform apply -var="env=prod" # Override variable
terraform apply -parallelism=20 # Run 20 operations in parallel (default: 10)Destroy all managed resources:
terraform destroy # Interactive
terraform destroy -auto-approve # Skip confirmation
terraform destroy -target=aws_instance.web # Destroy one resource onlyEquivalent to: terraform apply -destroy
Auto-format .tf files to canonical style:
terraform fmt # Format current directory
terraform fmt -check # Check if files are formatted (CI/CD)
terraform fmt -diff # Show what would change
terraform fmt -recursive # Format all subdirectoriesTip: Set up format on save in your editor. The terraform fmt -check flag is perfect for CI pipelines — it exits with code 1 if files aren't formatted.
Check syntax and internal consistency:
terraform validateSuccess! The configuration is valid.Catches: missing required arguments, invalid references, type mismatches. Does NOT catch: invalid AMI IDs, wrong instance types (use TFLint for that).
List all resources in state:
$ terraform state list
aws_instance.web
aws_security_group.web
aws_vpc.main
module.database.aws_db_instance.mainShow details of a specific resource:
$ terraform state show aws_instance.web
# aws_instance.web:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
id = "i-0abc123def456"
public_ip = "54.123.45.67"
# ...
}Rename a resource in state (without destroying it):
# Rename a resource
terraform state mv aws_instance.web aws_instance.app
# Move into a module
terraform state mv aws_instance.web module.app.aws_instance.webRemove a resource from state (Terraform forgets it, but the real resource stays):
terraform state rm aws_instance.webUse when: you want Terraform to stop managing a resource without destroying it.
terraform state pull > state.json # Download remote state
terraform state push state.json # Upload state (dangerous!)Bring an existing resource under Terraform management:
terraform import aws_instance.web i-0abc123def456
terraform import aws_s3_bucket.data my-bucket-name
terraform import module.vpc.aws_vpc.main vpc-12345678Workflow:
.tf fileterraform importterraform plan to verify no changes.tf file until plan shows no diffDeclarative import — no CLI needed:
import {
to = aws_instance.web
id = "i-0abc123def456"
}Then run terraform plan — it generates the configuration for you.
Show output values:
terraform output # All outputs
terraform output instance_ip # Specific output
terraform output -json # JSON format
terraform output -raw instance_ip # Raw value (no quotes)Useful for scripting:
# Use output in a script
IP=$(terraform output -raw instance_ip)
ssh ubuntu@$IPterraform apply -var="region=eu-west-1"
terraform apply -var-file="prod.tfvars"
terraform apply -var='tags={"env":"prod"}'
# Environment variables
export TF_VAR_region=eu-west-1
terraform applyManage multiple environments with the same configuration:
terraform workspace list # List workspaces
terraform workspace new staging # Create workspace
terraform workspace select prod # Switch workspace
terraform workspace show # Show current workspace
terraform workspace delete staging # Delete workspaceUse in configuration:
resource "aws_instance" "web" {
instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"
tags = {
Environment = terraform.workspace
}
}Interactive expression evaluator:
$ terraform console
> var.region
"us-east-1"
> length(var.subnets)
3
> cidrsubnet("10.0.0.0/16", 8, 1)
"10.0.1.0/24"
> exitGenerate a dependency graph:
terraform graph | dot -Tpng > graph.pngShow required providers:
$ terraform providers
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 5.0
└── provider[registry.terraform.io/hashicorp/random] >= 3.0export TF_LOG=DEBUG
terraform planLog levels: TRACE, DEBUG, INFO, WARN, ERROR.
| Flag | Purpose |
|---|---|
-auto-approve | Skip confirmation prompts |
-input=false | Disable interactive prompts |
-no-color | Disable color output |
-out=plan.tfplan | Save plan for later apply |
-json | Machine-readable JSON output |
-compact-warnings | Reduce warning verbosity |
-parallelism=N | Parallel operations (default 10) |
Typical CI pipeline:
terraform init -input=false
terraform fmt -check
terraform validate
terraform plan -input=false -out=plan.tfplan
terraform apply -input=false plan.tfplanLearn by doing with interactive courses on CopyPasteLearn:
The core workflow is init → plan → apply. Use fmt and validate in CI. Use state commands to inspect and reorganize managed resources. Use import to bring existing infrastructure under Terraform control. Use console to test expressions. Use -auto-approve and -input=false for automation.
Step-by-step guide to terraform import. Import existing AWS, Azure, and GCP resources into Terraform state. Includes import blocks (Terraform 1.5+)
Install and run Terraform on Ubuntu 26.04 LTS Resolute Raccoon. Covers sudo-rs as default, APT 3.2 rollback, Kernel 7.0, Wayland-only, ROCm, and building...
Learn the purpose and benefits of Terraform modules and how they enhance reusability, organization, and scalability in managing infrastructure as code.
Encountering the Inconsistent Dependency Lock File error in Terraform? This guide explains the causes and provides step-by-step solutions to resolve the.