Terraform interview question · Most asked
How do you refactor Terraform code without destroying resources? Explain moved blocks and state mv.
Summary
When you rename a resource or move it into a module, Terraform would otherwise plan to destroy the old address and create a new one. A moved block (Terraform 1.1+) records the old and new addresses in configuration, so the plan shows a move instead of a replacement; terraform state mv does the same imperatively.
Longer Answer
moved {
from = aws_instance.web
to = module.web.aws_instance.this
}
moved blocks are better for shared code because every workspace and pipeline applies them consistently and they can be reviewed. removed blocks (Terraform 1.7+) stop managing a resource without destroying it (replacing terraform state rm). Always check the plan shows moves, not destroys, before applying.
Key Points
- Renames look like destroy + create.
- moved blocks record address changes.
- removed blocks forget without destroying.
- Verify the plan shows moves.
More most-asked Terraform questions
- How do you handle secrets in Terraform?
- How would you run Terraform in CI/CD?
- What is Terraform state, why is it needed, and where should it be stored?
- count or for_each: when do you use each?
- Walk through terraform init, plan and apply. What does each do?
- What is Terraform, and how does it work at a high level?
- What are Terraform modules, and how do you design good ones?
- A terraform plan wants to destroy and recreate a database. What do you do?