Terraform Tutorial — State Commands
Terraform provides several state subcommands for inspecting and modifying state without editing the JSON file directly.
terraform state list
List all resources in state:
$ terraform state list
aws_s3_bucket.main
aws_instance.web
aws_vpc.production
aws_subnet.public[0]
aws_subnet.public[1]
module.vpc.aws_vpc.this
Filter with a pattern:
$ terraform state list aws_subnet.*
aws_subnet.public[0]
aws_subnet.public[1]
terraform state show
Show details of a specific resource:
$ terraform state show aws_instance.web
# aws_instance.web:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
arn = "arn:aws:ec2:us-east-1:123456789:instance/i-0abc123def"
id = "i-0abc123def"
instance_type = "t3.micro"
public_ip = "54.123.45.67"
subnet_id = "subnet-0abc123"
tags = {
"Name" = "web-server"
"Environment" = "dev"
}
}
terraform state mv
Rename a resource in state (without destroying/recreating):
# Rename a resource
$ terraform state mv aws_instance.web aws_instance.app_server
# Move a resource into a module
$ terraform state mv aws_s3_bucket.main module.storage.aws_s3_bucket.main
When to use:
- You renamed a resource in your
.tffile and don’t want Terraform to destroy/recreate it - You’re refactoring configuration into modules
terraform state rm
Remove a resource from state (Terraform “forgets” it):
$ terraform state rm aws_instance.web
Removed aws_instance.web
Successfully removed 1 resource instance(s).
⚠️ Warning: The real resource still exists in AWS. Terraform just stops managing it. Use this when you want to hand off a resource to another Terraform config or manage it manually.
terraform import
Import an existing resource into Terraform state:
$ terraform import aws_instance.web i-0abc123def456
aws_instance.web: Importing...
aws_instance.web: Import complete!
You must have a matching resource block in your configuration:
resource "aws_instance" "web" {
# Configuration will be populated after import
}
After importing, run terraform plan to see what arguments need to be added to match the real resource.
terraform state pull / push
Download or upload the state file (for advanced operations):
# Download current state to stdout
$ terraform state pull > state_backup.json
# Upload state from file (dangerous!)
$ terraform state push state_backup.json
Command Summary
| Command | Purpose | Modifies State? |
|---|---|---|
state list |
List all resources | No |
state show |
Show resource details | No |
state mv |
Rename/move a resource | Yes |
state rm |
Remove from state | Yes |
import |
Add existing resource | Yes |
state pull |
Download state | No |
state push |
Upload state | Yes |
What’s Next?
Let’s wrap up with best practices for managing state in production environments.