Terraform Advanced — state mv & Refactoring
Rename resources, move them between modules, or split states — without destroying infrastructure.
Rename a Resource
# Renaming in code: aws_instance.web → aws_instance.app
# Without state mv: Terraform destroys web, creates app
# With state mv:
terraform state mv aws_instance.web aws_instance.app
# Now plan shows no changes
Move Into a Module
# Moving a resource into a module
terraform state mv aws_vpc.main module.networking.aws_vpc.main
Move Between State Files
# Pull resource from source state
terraform state mv \
-state=networking/terraform.tfstate \
-state-out=compute/terraform.tfstate \
aws_security_group.app aws_security_group.app
moved Block (Terraform 1.1+)
Declarative refactoring — no manual state commands:
# Tell Terraform you renamed a resource
moved {
from = aws_instance.web
to = aws_instance.app
}
# Tell Terraform you moved into a module
moved {
from = aws_vpc.main
to = module.networking.aws_vpc.main
}
$ terraform plan
# aws_instance.app will be moved from aws_instance.web
# No destroy/create!
💡 Production Tip: Prefer
movedblocks overterraform state mv. They’re version-controlled, reviewable, and work in CI/CD.
List and Show State
# List all resources in state
terraform state list
# Show details of a specific resource
terraform state show aws_instance.app
# Pull entire state to local file
terraform state pull > backup.tfstate
What’s Next?
Recover from deleted state files.