A Rename Can Look Like Destroy and Create
A pull request renames one label. resource "local_file" "greeting" becomes resource "local_file" "hello". The filename, the content, the provider and the directory are untouched, so the reviewer reads the diff as a rename and approves it.
The plan does not read intent; it reads addresses. Before planning, Terraform builds two sets: the addresses the state records and the addresses the configuration declares. The old address is in the first set and missing from the second, so it is scheduled for destruction; the new address is in the second set and absent from the first, so it is scheduled for creation.
The summary gives it away: Plan: 1 to add, 0 to change, 1 to destroy.
Nothing about the object changed. Everything about its identity did.
The same arithmetic explains every refactor. State addresses minus configuration addresses gives destroys, and the reverse gives creates. Identical arguments never move an address between the two columns.
For a local file the damage is visible. Both addresses resolve to the same path, so the create writes the file and the destroy deletes it. Whichever the graph schedules second wins: create first and the file you just wrote is removed by the address you abandoned; destroy first and there is a window with no file and a replacement with a new identity.
Replacement rules do not span two addresses
create_before_destroy reorders the destroy and create inside one address's replacement. These are two addresses with no dependency edge between them, so the setting never applies.
Cloud objects fail louder. A bucket name, DNS record, IAM role or secret name is unique in an account or zone, so the create asks for a name the old object still holds and the provider refuses. When the name is generated, the create succeeds and for the length of the apply you own two objects, one of them carrying the data.
Figure 1 traces the split. A label change becomes one address disappearing and another appearing, and the plan answers each side separately.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Edit: label greeting becomes hello"] --> B["New address: local_file.hello"]
A --> C["Old address: local_file.greeting"]
B --> D{"Recorded in state?"}
C --> E{"Still declared?"}
D -->|"no"| F["Plan: one create"]
E -->|"no"| G["Plan: one destroy"]
F --> H["Apply order decides the damage"]
G --> H
H -->|"create first"| I["A unique name is still held by the old object"]
H -->|"destroy first"| J["A window with no object, then a new id"]
I --> K["Replacement rules never span two addresses"]
J --> K
K --> L["moved block: one address rewritten, zero changes"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,D,E primary;
class B,C,F,G secondary;
class H warn;
class I,J,K danger;
class L ok;
Figure 2 puts the two views side by side: what the diff meant, and what the address comparison produced.
That gap is what the rest of this article fills. Terraform lets you state the relationship yourself: a moved block when the object survives and only its name changes, and a removed block when you intend to stop managing it. Everything else is an imperative command against a state file.
Use Moved Blocks as Versioned Migration Instructions
A moved block is a sentence about the past, written in the present tense. It says this address used to mean that object, and it still does. The from argument takes the old address, to takes the new one, and the block is written in the module where that new address appears.
Terraform resolves the move before planning. If a record exists at the old address, it rewrites the address to the new one and continues as if the object had always lived there.
The plan shows one annotation: # local_file.greeting has moved to local_file.hello — and a zero-change summary: Plan: 0 to add, 0 to change, 0 to destroy.
No provider call performs the move, which is why it costs nothing and works the same for a file, a database and a DNS record. If an attribute changes in the same commit, the plan reports the move and the change against the moved object.
The move ships with the module
The block lives inside the module source, so it travels with the module version and is replayed by every plan against every state that has not caught up. A team on version 1.2 and a workspace created yesterday converge on the same addresses, because evaluation happens whenever the configuration runs, not once when a human remembered a command.
Chains are allowed. Keep both the a → b and b → c entries, and Terraform resolves a through b to c in one apply. Deleting the first block breaks any state that never applied the intermediate version.
Moving into a module is the same sentence with a longer address. The block lives in modules/web/main.tf, the root gains a module "web" call, and the migration names both sides. A whole module call moves the same way: one block then covers every resource inside it.
The count-to-key conversion is the same tool. One moved block per old index maps each position to its new key: web, api, batch. Each indexed object is then treated as if it had been created under its name.
Move first and verify, then delete the entry. A destination the configuration no longer declares has nothing to attach to, and the plan degenerates into the pair of changes the block prevented.
Each limit is a plan-time error, not an apply-time surprise. The block is deliberately strict about what it can prove:
| Limit | Rule | Consequence |
|---|---|---|
| State boundary | A move operates inside one root's state only | It cannot cross state files; splitting a root is a different procedure |
| Destination | to must be an address the new configuration declares | Plan-time error: reference to an undeclared resource |
| Shared destination | Two moves cannot target the same address | Plan-time error: ambiguous move |
| Object kind | Managed objects cannot become data, and types rarely change | Refused unless the provider documents a compatible migration |
| Module scope | A module may speak only about its own objects and its children | A child cannot move a parent resource |
Use Moved Blocks as Versioned Migration Instructions
Execution status: design-only. This card sets up the module and stops at the plan; the apply and identity comparison are in the final lab. Versions are Terraform CLI 1.17.1 and hashicorp/local 2.9.1, current on 5 November 2026.
Prerequisites. Terraform 1.17.1 on PATH and the root module below applied once. No cloud account, no credential, no cost.
Minimal setup. Start with both objects in the root module:
# main.tf — before the refactor
terraform {
required_version = "= 1.17.1"
required_providers {
local = {
source = "hashicorp/local"
version = "2.9.1"
}
}
}
resource "terraform_data" "service" {
input = "web"
}
resource "local_file" "greeting" {
filename = "${path.root}/greeting.txt"
content = "hello from ${terraform_data.service.output}\n"
}
output "service_id" {
value = terraform_data.service.id
}
output "file_id" {
value = local_file.greeting.id
}
Use the root-relative path. In the root, path.root and path.module resolve to the same directory; inside a child module only path.root keeps pointing at the root. With the module-relative form, the filename gains a subdirectory the moment the block moves — a real attribute change wearing the costume of a refactor.
- Run
terraform init -input=falseandterraform apply -auto-approve, thenterraform state list -id. Record both ids. - Create
modules/web/main.tfand move both resource blocks into it, keepingpath.root. The child inherits the local provider without aproviderblock. - Add outputs to the child (
service_id,file_id) and reduce the root to the module call, the two moves and the rewired outputs:
# main.tf — after the refactor
module "web" {
source = "./modules/web"
}
moved {
from = terraform_data.service
to = module.web.terraform_data.service
}
moved {
from = local_file.greeting
to = module.web.local_file.greeting
}
output "service_id" {
value = module.web.service_id
}
output "file_id" {
value = module.web.file_id
}
- Run
terraform init -input=false,terraform fmt -checkandterraform plan. Expect twohas moved toannotations and0 to add, 0 to change, 0 to destroy. - Read
filenamein the plan. It must still be the absolute path ofgreeting.txtbeside the rootmain.tf; a path undermodules/web/means the plan will show a replacement. - For the keyed variant, apply a three-instance
countversion, convert it tofor_each, and add onemovedblock per index. Confirm moves, not replacements.
Expected observation. Two address rewrites, no provider operations, a zero-change summary, and module.web. on both to addresses.
Failure check. A moved block pointing at an undeclared address should be refused. Two blocks sharing a destination should fail as ambiguous. A path.module filename should show a replacement even though the move succeeded.
Cost and cleanup. Zero, and state is a few kilobytes. Keep the directory for the final lab, then terraform destroy -auto-approve.
Figure 3 follows the evaluation and the branches where it stops.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Plan starts"] --> B{"Any moved block in this module?"}
B -->|"no"| B1["Addresses compared exactly as written"]
B -->|"yes"| C["Resolve from and to relative to this module"]
C --> D{"Is to declared in configuration?"}
D -->|"no"| D1["Error: reference to an undeclared resource"]
D -->|"yes"| E{"Do two moves share a destination?"}
E -->|"yes"| E1["Error: ambiguous move"]
E -->|"no"| F{"Is there a record at from?"}
F -->|"no"| G["Nothing to move, planning continues normally"]
F -->|"yes"| H{"Is a record already at to?"}
H -->|"yes"| H1["Error: destination address already exists"]
H -->|"no"| I["Rewrite the instance address before planning"]
I --> J["Plan: zero add, zero change, zero destroy"]
J --> K["Apply writes the new address, same object id"]
K --> L["Keep the block for every state that is older"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,C,D,E,F,H primary;
class G,I,J,K secondary;
class B1,D1,E1,H1 danger;
class L ok;
The failure branches are all configuration errors, which is the point: a move that cannot be proven becomes a plan you cannot apply, not an apply that quietly recreates production.
Remove Management Deliberately with Removed Blocks
Three different intentions hide behind "remove this resource", and Terraform has three different answers.
Deleting the block is the ordinary answer. Desired state no longer includes the object, so the next plan proposes a destroy. The plan is a proposal, a reviewer sees the address, and the apply removes it. Deleting a whole module block scales the same logic up: eight objects disappear and eight destroys appear in one plan — nobody reads address nine.
The difference is where the intent lives and whether a reviewer can see it:
| Method | Where the intent lives | What the plan does | Reviewable |
|---|---|---|---|
| Delete the resource block | Configuration | One destroy per address; deleting a module block destroys every object inside it | Yes, as a large diff |
removed block with destroy = false | Configuration | Forgets the address, calls no provider, leaves the object running | Yes, in the same pull request |
removed block without the lifecycle | Configuration | Destroys the object, because destroy defaults to true | Yes, but the intent reads as a removal |
terraform state rm | A terminal against one state file | Forgets the address immediately, with no plan and no record in the repository | No |
A removed block is the only way to say "stop managing this" in configuration. It names the old address and puts the decision in a nested lifecycle block.
destroy defaults to true
The decision is one argument:
removed {
from = local_file.greeting
lifecycle {
destroy = false
}
}
Without the lifecycle block, destroy defaults to true, so the block still destroys the object. The block records intent and allows destroy-time provisioners, but the infrastructure goes away. Only destroy = false means forget rather than delete.
With destroy = false, the object becomes unmanaged. The plan annotates the address as no longer managed and states that the object will not be destroyed. Nothing calls the provider. After the apply the state has no record, the object keeps running, and the next plan does not mention it.
Billing continues and drift becomes invisible. That is the trade, and it is usually right when another team or tool is taking over.
The third answer is terraform state rm. It is immediate, changes no configuration and leaves no trace in the repository.
Prefer the block whenever the removal is planned. It ships in the same pull request as the deleted configuration, a reviewer sees it, and every workspace running that version performs it. state rm is a manual act against one state file, invisible to review and easy to forget in the second environment — where the object stays managed until a plan destroys it months later.
Keep the removed block for at least one release. Once no state contains the address it does nothing, and removing it is safe because it has no destination to preserve.
A handoff that exists only in Terraform's memory is not a handoff. Tag the object with its new owner, note the date and address in the module README, and open the ticket that makes someone else responsible.
Know When Imperative State Commands Are Necessary
State commands are incident tools. They write state directly, with no plan, policy check or approval gate, so they belong behind a change freeze and a named operator.
They are still sometimes the only option:
- The state was written by a configuration that no longer exists. A hotfix branch applied a rename, was never merged, and the main branch now plans to destroy the object.
- A provider address changed. A provider moved to an internal mirror or fork, and every state still records the old source.
- A module was published without a
movedblock. Consumers have old addresses and no upgrade path. - Two roots must exchange one object quickly and the removed-then-import procedure is too slow for the window you have.
The protocol matters more than the command. Announce the change and pause every automated writer: CI applies, scheduled plans, a colleague's half-finished branch. Confirm nobody else holds the lock; a held lock means a writer, and force-unlock is not a diagnosis.
Snapshot before you touch anything. Keep the copy out of Git because it holds every attribute in cleartext, record the serial and lineage, and run a plan first. If the state is already drifting, you cannot tell your edit from the drift afterwards.
terraform state mv rewrites one binding. The -dry-run flag reports what the address matches without changing anything, and the command refuses to move between resource types or kinds of object. Quote any address containing brackets.
Local state writes a backup beside the file. Terraform creates terraform.tfstate.backup; copy it somewhere durable before running the next write. The file-oriented flags work on local state only, so they cannot move an object between two remote backends in one step.
terraform state rm forgets, with no dry run. The only preview is terraform state list before and after. Use it when the object must leave before the code declaring it can be deleted.
The replace-provider command relabels provider ownership. Change required_providers, run terraform init so the new provider is installed, then pass the old and new source addresses to the command in the widget. If the schemas disagree, the next plan shows attribute changes; investigate them rather than accepting the noise.
Never hand-edit the state file
Hand-editing JSON is editing a live database with a text editor. The private field is provider-owned, schema_version drives an upgrade path, and a file that parses can still describe objects incorrectly.
terraform state push overwrites a whole snapshot and refuses a lineage mismatch unless forced. It is the restore path, not a migration tool.
Finish the same way every time. Run terraform state list for the addresses, a plan for no changes, and write the backup path into the change record. If the plan shows anything unexpected, restore the snapshot before investigating.
Split a Root Without Two States Owning One Object
Roots get split for good reasons: an eleven-minute plan, a blast radius that includes the database, or a lock contested every afternoon. The refactor is mechanical; the risk is ownership.
The invariant is absolute: at any moment, one object is managed by at most one state.
One object, one state
Two owners is the dangerous state, because both plans look clean. Each root believes it is authoritative, neither reports drift caused by the other, and the first destroy in either root deletes an object the other still owns. The other root then recreates it with a new id, and every reference to the old id — a DNS target, a bucket policy, a secret ARN — points at something gone.
Zero owners is the safe intermediate. Nobody can destroy what nobody manages, and the object simply sits there while the transfer completes.
So the transfer goes through zero, never through two. In order:
- Freeze both roots. Announce the window, pause CI in both, and confirm no run is in flight. Snapshot both states with
terraform state pull, then record both serials and lineages. - Record the identity. Run
terraform state list -idin the source and write down the provider id. That string, not the address, is the evidence the object survived. Note any unique name or tag the destination needs. - Write the destination configuration. Declare the resource in the new root with arguments that resolve to the same real object. Do not apply yet.
- Release from the source. Add a
removedblock for the address withdestroy = false, then apply. The source plan should show no provider operations, the address should vanish fromterraform state list, and the object should still exist. Verify that last part outside Terraform. - Adopt in the destination. Add an
importblock whosetois the new address and whoseidis the string from step 2, then apply. The provider reads the object; it does not create anything, and it must support import — a resource that cannot be imported cannot change roots without recreation, which is a fact to establish before step 1. Remove the block afterwards, because the next plan otherwise reports that the resource is already managed. - Prove it. Both roots must plan clean. The destination's
terraform state list -idmust show the recorded id, and the source must not mention the address. Only then close the window.
Step 5 before step 4 is the mistake that costs data: for as long as both applies take, two states own one object. Skipping step 4 and deleting the source block instead is the same mistake with a destroy plan attached.
After the source has forgotten the object, a plain git revert of the removed block does not restore ownership. It declares a block whose address has no record, so the plan creates a new object and leaves the real one untracked. Recovery is an import, not a revert.
Figure 4 draws the ownership timeline and the two ways to get it wrong.
If both roots share a backend and you can hold the locks, terraform state mv -state-out against pulled local copies is faster, but it is two writes with no atomicity between them. A failed second push leaves zero owners with no configuration change explaining why.
Recovery follows the failed step. A failed release means nothing changed: fix the block and re-apply. A failed adopt means the object is unowned and safe: correct the destination and apply again, or import it back into the source. Neither case requires recreating the object, and both require that nobody applies the source in the meantime still believing it owns the address.
Prove a Refactor Has No Infrastructure Changes
A refactor is finished when you can show, not assume, that the infrastructure did not move. The evidence pack is short:
| Evidence | How to capture it | What it proves |
|---|---|---|
| Addresses before and after | terraform state list and -id in each directory | Old addresses are absent; new ones are present with the intended prefix |
| The plan | Saved with terraform plan -out=tfplan, then rendered with terraform show tfplan | Each address appears as has moved to, not as a + and - pair |
| The summary | The plan's final line | Plan: 0 to add, 0 to change, 0 to destroy; anything else is a real change needing its own justification |
| Object identity | The provider id, plus ls -li for the local file | The same id before and after; the inode catches a rewrite because the file id is derived from content |
| State metadata | jq over the state file | lineage unchanged, serial increased; a new lineage means a different state |
The plan is the strongest witness and the easiest to misread. A move that also changes an attribute produces a real diff, and that diff is not evidence the move failed. Hence the baseline: plan before the refactor, confirm it is empty, then plan after and confirm the only differences are the intended ones.
terraform plan -detailed-exitcode turns that judgement into an exit code: 0 for no changes, 2 for changes, 1 for an error. A CI job expecting 0 fails loudly if a move silently became a replacement. The command exits 2 happily on a plan full of destroys, so the gate only protects you if the expected value is 0 and not "anything but 1".
A negative control makes the evidence convincing. In a copy of the directory, delete the moved blocks and plan again. Expect one create and one destroy at the two addresses: the outcome the blocks prevented, demonstrated rather than asserted.
Move the service into a module
Execution status: design-only. The sequence was not recorded as a single run; it follows the plan from the previous card. Versions are Terraform CLI 1.17.1 and hashicorp/local 2.9.1, current on 5 November 2026.
Prerequisites. The directory from the configuration card, with the plan showing two moves and no changes. No cloud account or credential.
- Save
terraform state list -idtoevidence/addresses-before.txtand note the UUID forterraform_data.service. - Record
ls -li greeting.txt. The id alone cannot distinguish a rewrite from a replacement for this resource; the inode can. - Run
terraform plan -out=tfplan, thenterraform show tfplan. Confirm the only annotations are the two moves and the summary is zero on all three counters. - Apply with
terraform apply tfplan. A saved plan is applied exactly as reviewed; re-planning now would compare against a state that already changed. - Save
terraform state listtoevidence/addresses-after.txt. Expectmodule.web.terraform_data.serviceandmodule.web.local_file.greeting, with no root-level counterpart. - Compare
terraform state list -idand the inode with steps 1 and 2. Either difference means the plan was not a move. - Run
terraform plan -detailed-exitcodeand readecho $?. Expect 0; a 2 means something is still changing. - Copy the directory with
cp -R . ../p19-control, delete bothmovedblocks there, and plan without applying. Expect one create and one destroy. - Check
jq '{serial, lineage}' terraform.tfstate. The lineage should match the earlier snapshot and the serial should be higher.
Expected observation. Two addresses, two ids, one clean plan. The address and serial changed, the lineage did not, and the object's identity is the one you recorded before the refactor.
Failure check. A changed inode means the file was rewritten, usually from a path.module filename. A plan summary of 1 to add, 0 to change, 1 to destroy in the control copy is the correct negative result. A destroy in the real directory means a moved block is missing or its destination does not match the configuration.
Cost and cleanup. Zero provider or cloud charges: two directories, a few kilobytes of state, seconds per plan. Run terraform destroy -auto-approve in the refactored directory so the module addresses are removed, then delete the control copy, the saved plan and the evidence directory.
A refactor is a claim about history: these addresses are new, these objects are old, and the difference is a record-keeping change rather than an infrastructure event. The moved block makes that claim executable, the removed block makes the end of ownership explicit, and the plan makes both falsifiable. Everything else is a command run in a hurry.
Next in the Series
In Credentials and Secrets: Follow the Value End to End, we'll explore Use short-lived authentication and understand where secret values can still be persisted.