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

← All Terraform questions