0
0
TerraformHow-ToBeginner · 3 min read

How to Use Terraform State mv Command: Syntax and Examples

Use the terraform state mv command to move a resource from one address to another within the Terraform state file. This helps when renaming resources or reorganizing your configuration without recreating infrastructure. The syntax is terraform state mv [options] SOURCE DESTINATION.
📐

Syntax

The terraform state mv command moves a resource from a source address to a destination address in the Terraform state file.

  • SOURCE: The current resource address in the state.
  • DESTINATION: The new resource address you want to assign.
  • [options]: Optional flags like -state to specify a custom state file.

This command updates the state only; it does not change your actual infrastructure.

bash
terraform state mv [options] SOURCE DESTINATION
💻

Example

This example shows how to rename a resource in the Terraform state from aws_instance.old_name to aws_instance.new_name. This is useful if you renamed the resource in your configuration and want the state to match without destroying and recreating the instance.

bash
terraform state mv aws_instance.old_name aws_instance.new_name
Output
Moved aws_instance.old_name to aws_instance.new_name
⚠️

Common Pitfalls

  • Wrong addresses: Using incorrect resource addresses causes errors. Always check addresses with terraform state list.
  • State file mismatch: Moving resources without updating your configuration leads to drift. Update your Terraform files to match the new resource names.
  • Not backing up state: Always back up your state file before moving resources to avoid accidental loss.
bash
## Wrong way (incorrect source address)
terraform state mv aws_instance.wrong_name aws_instance.correct_name

## Right way (check addresses first)
terraform state list
terraform state mv aws_instance.old_name aws_instance.new_name
📊

Quick Reference

CommandDescription
terraform state mv SOURCE DESTINATIONMove resource in state from SOURCE to DESTINATION
terraform state listList all resources in the current state
terraform state pullDownload the current state file
terraform state pushUpload a local state file

Key Takeaways

Use terraform state mv to rename or move resources in the Terraform state safely.
Always verify resource addresses with terraform state list before moving.
Update your Terraform configuration files to match the new resource names after moving.
Back up your state file before running terraform state mv to prevent data loss.
terraform state mv changes only the state, not the actual infrastructure.