Moved Blocks and Resource Refactoring
What you'll learn: How to safely rename or restructure Terraform resources without destroying and recreating your actual infrastructure.
The Refactoring Problem
As your Terraform codebase evolves, you'll often need to rename resources, reorganize modules, or change resource addresses for clarity. Normally, renaming a resource in your configuration causes Terraform to see it as a deletion of the old resource and creation of a new one—potentially destroying live infrastructure!
The moved block solves this by telling Terraform "this resource didn't disappear; it just moved to a new address."
How Moved Blocks Work
Think of moved blocks like forwarding addresses for mail. When you move houses, you tell the post office where to redirect your letters. Similarly, when you refactor resource addresses, you tell Terraform where the resource "moved" in your configuration.
Basic syntax:
moved {
from = aws_instance.old_name
to = aws_instance.new_name
}
When you run terraform plan, Terraform updates the state file to reflect the new address—without touching the actual infrastructure. The cloud resource stays exactly as it is; only Terraform's internal bookkeeping changes.
Common Use Cases
- Renaming resources for better clarity
- Moving resources into or out of modules
- Reorganizing module structure
- Changing
countorfor_eachkeys
After applying the moved block and verifying the state is correct, you can safely remove the moved block from your configuration in future commits.
Key Takeaway: Use moved blocks to refactor Terraform resource addresses cleanly, updating state without destroying infrastructure—like giving Terraform a forwarding address for renamed resources.