0
0
Terraformcloud~5 mins

Terraform state mv for refactoring - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you change the names or locations of resources in your Terraform code, the state file still remembers the old names. Terraform state mv helps you update the state file to match your new code without destroying or recreating resources.
When you rename a resource block in your Terraform configuration to better reflect its purpose.
When you move a resource from one module to another in your Terraform project.
When you split a large Terraform configuration into smaller modules and need to update the state accordingly.
When you want to reorganize your infrastructure code but keep the existing resources intact.
When you fix a typo in a resource name after initial deployment.
Commands
This command lists all resources currently tracked in the Terraform state. Use it to find the exact resource address you want to move.
Terminal
terraform state list
Expected OutputExpected
aws_instance.my_old_instance aws_s3_bucket.my_bucket module.network.aws_vpc.main
This command moves the resource named aws_instance.my_old_instance in the state file to aws_instance.my_new_instance. It updates the state to match your new resource name without changing the actual infrastructure.
Terminal
terraform state mv aws_instance.my_old_instance aws_instance.my_new_instance
Expected OutputExpected
Moved aws_instance.my_old_instance to aws_instance.my_new_instance
Run this again to verify that the resource address has been updated in the state file.
Terminal
terraform state list
Expected OutputExpected
aws_instance.my_new_instance aws_s3_bucket.my_bucket module.network.aws_vpc.main
Key Concept

If you rename or move resources in your Terraform code, use terraform state mv to update the state file so Terraform knows the resources are the same.

Common Mistakes
Renaming the resource in code but not running terraform state mv
Terraform will think the old resource was deleted and a new one created, causing unnecessary destruction and recreation.
Always run terraform state mv to update the state file to match your new resource names.
Using incorrect resource addresses in terraform state mv command
The command will fail or move the wrong resource, causing state inconsistencies.
Use terraform state list to find exact resource addresses before moving.
Summary
Use terraform state list to see current resources in the state file.
Run terraform state mv old_resource_name new_resource_name to update the state after renaming or moving resources.
Verify the move by listing the state again to ensure the resource address is updated.