Terraform Advanced — Recovering Deleted State
What to do when your state file is lost or corrupted.
Recovery from S3 Versioning
# List state file versions
aws s3api list-object-versions \
--bucket my-tf-state \
--prefix prod/terraform.tfstate
# Restore a previous version
aws s3api get-object \
--bucket my-tf-state \
--key prod/terraform.tfstate \
--version-id "abc123" \
restored.tfstate
# Push it back
terraform state push restored.tfstate
💡 Production Tip: Always enable versioning on your state bucket. It’s your safety net.
Re-Import Everything
When state is completely gone:
# 1. List existing resources (AWS CLI, console, etc.)
aws ec2 describe-instances --filters "Name=tag:ManagedBy,Values=terraform"
# 2. Import each resource
terraform import aws_instance.app i-0abc123def456
terraform import aws_vpc.main vpc-0abc123
terraform import aws_subnet.private[0] subnet-0abc123
# 3. Verify
terraform plan
# Should show no changes if imports match code
Import Block (Terraform 1.5+)
import {
to = aws_instance.app
id = "i-0abc123def456"
}
import {
to = aws_vpc.main
id = "vpc-0abc123"
}
terraform plan -generate-config-out=generated.tf
terraform apply
Prevention Checklist
✅ S3 versioning enabled on state bucket
✅ DynamoDB table for locking
✅ Regular state backups (terraform state pull > backup.tfstate)
✅ State bucket replication to another region
✅ Deletion protection on state bucket
What’s Next?
Practice debugging and state surgery.