पाठ 20 / 25

Renaming With moved Blocks

Tell Terraform the resource moved.

Refactor addresses, keep the resource

Renaming a resource or moving it into a module changes its address. Without help, Terraform sees one resource removed and another added, and plans to destroy and re-create it. A moved block (from old address, to new address) records the rename so the plan shows "has moved" with no infrastructure change. Keep moved blocks for a while so every environment and colleague picks them up, then remove them.

Change code without changing infrastructure

moved blocks rename safely, import blocks adopt existing resources.

Three ideas: moved blocks, renames without moved, import.
Figure 7.1 — moved, rename and import.

A rename recorded with moved, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. After renaming local_file.cfg to local_file.app_config and adding a moved block, the plan reports "has moved" and 0 to add, 0 to change, 0 to destroy.

grep -A3 "^moved" main.tf
terraform plan -no-color | grep -E "has moved|Plan:"

Output:

moved {
  from = local_file.cfg
  to   = local_file.app_config
}
  # local_file.cfg has moved to local_file.app_config
Plan: 0 to add, 0 to change, 0 to destroy.

Use moved for module extraction

When moving resources into a module, add moved blocks from the old address to module..

.

त्वरित जाँच: What does a moved block prevent?

  • All future changes
  • Destroying and re-creating a resource just because its address changed
  • Provider upgrades
  • Variable validation
Answer

Destroying and re-creating a resource just because its address changed — Refactor code, not infrastructure.