Terraform count to for_each: migrate identity first
Rehearse unchanged inventory first, require exact previous_address and no-op actions, then separately delete an item and retain compatibility history.
Quick answer
When changing Terraform from `count` to `for_each`, map each existing numeric address to a stable key with a `moved` block before changing the managed inventory. Verify the old-to-new identity mapping and the resulting actions in the plan. An address move can preserve an object, but it does not prevent a separate argument change from updating or replacing it.
On this page
When changing Terraform from count to for_each, map each existing numeric address to a stable key with a moved block before changing the managed inventory. Verify the old-to-new identity mapping and the resulting actions in the plan. An address move can preserve an object, but it does not prevent a separate argument change from updating or replacing it. [1][2][3]
Why does removing a list entry change unrelated instances?#
Scenario: a fictional platform module manages queues named alpha, beta and gamma through an ordered list. The resource uses count, and each instance reads the list element at its index. An operator wants to remove beta. Deleting its list entry shifts gamma into beta's former numeric position, while gamma's former position disappears. The intended inventory change and the address change have become entangled.
Terraform's count identifies instances by numeric index. It does not know that a particular list value is the domain identity you intended to preserve. With for_each, keys identify instances, so a stable key can survive changes to neighboring entries. A key rename is still an address change, and an argument that a provider considers replacement-sensitive can still require replacement. [2][3]
Do not promise that every reordered list destroys resources. The actions depend on the resource type, changed arguments and provider behavior. The general problem is identity drift: an existing address can now refer to a different intended object. Whether the plan proposes an update or replacement, the reviewer must establish which real object each address represents. [1][2][3]
The first plan should preserve the inventory; a later plan can remove beta. First, can the existing inventory keep its identity under keyed addresses? Then, what should happen when a business object is removed? Keeping those stages separate makes an unexpected deletion easier to diagnose than a combined change that mixes address moves, values and removals.
Establish the mapping from state, not today's list order#
Read the actual workspace state and compare it with the configuration revision that created those instances. An assumed list order copied from a recent branch may already differ from the deployed mapping. Record the old address, intended stable key and an identifying attribute for every instance before writing any move. Inspect private state only in the authorized environment; it can contain sensitive values. [1][6]
For the fictional queue inventory, the proposed mapping is explicit:
| Existing address suffix | Verified object identity | New address suffix |
|---|---|---|
| Numeric index 0 | alpha | ["alpha"] |
| Numeric index 1 | beta | ["beta"] |
| Numeric index 2 | gamma | ["gamma"] |
If different workspaces have different ordering, a shared mapping can be correct in one and wrong in another. Stop and resolve that variation rather than trying the same move everywhere. Module boundaries and resource addresses must also match the actual configuration path. A shortened address in a diagram is not a valid substitute for the full address Terraform expects. [1]
Pick keys that the team intends to keep stable, are known while planning and are safe to display in addresses. for_each has known-value and sensitivity restrictions. A secret, a generated remote identifier or a key that changes whenever a display name changes creates a different migration problem. Use a durable non-sensitive identity and keep mutable labels in values when that matches the domain. [3]
Rehearse with built-in state instead of a cloud account#
The following local fixture uses terraform_data, which is available through Terraform's built-in provider. It demonstrates address and lifecycle behavior without provisioning a queue or requiring a cloud account. It does not model the replacement rules of a real queue provider. Run it in an empty disposable directory with local state, never in the production module. [4]
terraform {
required_version = ">= 1.4.0"
}
locals {
queue_names = ["alpha", "beta", "gamma"]
}
resource "terraform_data" "queue" {
count = length(local.queue_names)
input = local.queue_names[count.index]
}The minimum version here covers the built-in fixture resource. The moved mechanism itself is documented for Terraform v1.1 and later. Keep the tested CLI version in the review record rather than claiming that a current documentation example was executed with the latest release. [1][4]
Initialize and create only this disposable fixture's state. It has no provisioners and no remote backend. An apply is necessary to establish prior objects for the migration rehearsal; in a real infrastructure repository, an apply would require the normal release controls. The daily editorial process does not apply any production infrastructure. [4][6]
terraform init -input=false
terraform apply -input=false -auto-approve
terraform state listAfter the baseline exists, replace the resource's repetition mode while preserving the complete inventory and its values. Use address expressions in moved blocks; do not quote the whole expression as if it were an ordinary string. Only the map key inside the address is a string. [1]
locals {
queues = {
alpha = "alpha"
beta = "beta"
gamma = "gamma"
}
}
resource "terraform_data" "queue" {
for_each = local.queues
input = each.value
}
moved {
from = terraform_data.queue[0]
to = terraform_data.queue["alpha"]
}
moved {
from = terraform_data.queue[1]
to = terraform_data.queue["beta"]
}
moved {
from = terraform_data.queue[2]
to = terraform_data.queue["gamma"]
}The baseline and replacement snippets are alternatives, not declarations to concatenate. Leaving both versions of the same resource in the directory is a configuration error. In the real module, preserve unchanged arguments and provider wiring as well as inventory. Otherwise a plan can correctly recognize the address move while also proposing an unrelated update. [1][3]
Which plan evidence proves an identity-only migration?#
Save the migration plan and inspect its JSON representation. Terraform's plan output includes change actions and can include previous_address for a moved resource. A summary showing no creations or destructions is useful, but it does not alone prove that alpha and gamma were mapped correctly. The identity correspondence needs review too. [5][6]
terraform plan -input=false -out=migration.tfplan
terraform show -json migration.tfplan > migration.jsonimport json
with open("migration.json") as file:
plan = json.load(file)
expected = {
'terraform_data.queue["alpha"]': 'terraform_data.queue[0]',
'terraform_data.queue["beta"]': 'terraform_data.queue[1]',
'terraform_data.queue["gamma"]': 'terraform_data.queue[2]',
}
changes = {row["address"]: row
for row in plan.get("resource_changes", [])}
assert set(changes) == set(expected)
for address, previous in expected.items():
row = changes[address]
assert row.get("previous_address") == previous
assert row["change"]["actions"] == ["no-op"]
assert row["change"]["before"]["input"] == \
row["change"]["after"]["input"]This strict assertion belongs to the tiny fixture. A production plan may legitimately contain outputs, data sources or other reviewed changes, so scope assertions to the relevant managed resources and review everything outside that scope separately. Do not turn a permissive filter into a way to ignore an unexpected deletion elsewhere in the plan. [5]
Prove that the plan check rejects a missing move, a changed value and a wrong identity map. Omit a move and verify that the fixture no longer passes the identity-only gate. Change a value and verify that the no-op assertion fails. A deliberately wrong key mapping should fail the expected-address or value correspondence. These checks are more persuasive than a script that accepts any plan containing a move. [1][5]
Treat the saved plan and JSON as sensitive artifacts. Terraform warns that plan files can retain sensitive values even when terminal output conceals them. Do not attach a real workspace's unrestricted plan to a public article or issue. The fixture's values are fictional and deliberately contain no credentials or customer data. [6]
When should the inventory removal happen?#
After the unchanged-inventory address migration has been accepted in each relevant workspace, make the intended removal as a separate change. In the fixture, remove the beta map entry and plan again against the migrated state. The expected result is beta's deletion, with alpha and gamma retaining their keys and values. That is an inventory decision rather than evidence that keyed addressing failed. [3]
Do not carry an unexecuted migration plan into the second stage and assume the state has changed. The first plan describes proposed state movement; accepted execution establishes the new addresses. In production, use the normal apply process, then re-read state and create a fresh removal plan. A stale plan is not an inventory ledger. [1][6]
If production requirements allow the queue to survive after Terraform stops managing it, that is another lifecycle decision with its own procedure. Do not disguise “stop managing” as deleting a map key, because normal keyed-resource removal proposes destruction. Likewise, moving an address does not migrate the remote object to another region or account. Validate provider capabilities and object identity separately. [1][3]
After the state moves, reverting HCL alone may create another address mismatch. Before applying the migration, reverting the configuration can restore the old proposal. After state has moved, merely deleting move declarations and reverting the resource shape can produce another unwanted plan. A reverse mapping needs explicit review against current state. Preserve the last accepted configuration and evidence so recovery is based on known addresses. [1][6]
Why retain old moved blocks in a shared module?#
The module's newest consumer and oldest consumer may upgrade along different paths. Removing a move because one workspace already used it can leave a later upgrader without the address history it needs. HashiCorp documents removal of moved blocks as a breaking change and describes retaining historical moves to support upgrades. Treat compatibility as a property of the supported upgrade paths. [1]
Keep a mapping history with the module release rather than relying on an operator's terminal transcript. If the module renames the key again later, preserve a chain that explains how older states reach the new address. Test representative older-state fixtures whenever you change that chain. A no-op plan from a fresh empty state cannot test an upgrade path because it has no prior object to preserve. [1]
The local editorial rehearsal uses the installed Terraform CLI and built-in fixture, establishes disposable local state, and checks the proposed move, a missing-move control and the later inventory change. It does not execute a cloud provider migration or certify a production module's upgrade history. Record the actual result and CLI version with the plan artifacts before using the example as evidence. [4][5]
What should stop the migration before apply?#
Scenario: the proposed mapping says alpha belongs at the old first index, but the state shows beta there. Do not use the expected future configuration as proof that the state is wrong. Establish whether an earlier list reorder was applied, whether the selected workspace is correct, or whether the module path changed. A move should describe the object actually present at the old address, not the object a reviewer hoped to find.
An empty old address deserves the same attention. It can be normal for a fresh consumer that never had the old resource, but it can also mean the migration is pointed at the wrong state. Compare workspace identity, backend and known inventory before accepting a plan that creates everything from scratch. A move declaration that is harmless in an empty fixture is not evidence that a production object was preserved. [1]
Stop when the plan's object values no longer correspond to the mapping record, even if its action summary looks small. A keyed resource updated in place can still become the wrong business object if the move connected beta's state to alpha's configuration. Review an identifying attribute from before and after, and understand whether that attribute is mutable or merely a display label. The expected no-op fixture deliberately removes this ambiguity.
Check output consumers too. A resource-address migration can change the shape of a module output from a list to a map if the configuration exposes repetition directly. Preserve a compatibility output or introduce an explicit interface change rather than assuming downstream consumers adapt automatically. Test the documented module interface alongside the state mapping; stable remote objects do not guarantee stable configuration consumers. [2][3]
If drift or an unrelated provider change appears in the plan, separate or explain it before accepting the identity migration. Do not disable refresh simply to obtain a cleaner summary: that changes what the plan observes. HashiCorp warns that skipping refresh can yield an incomplete or incorrect proposal. A review needs the current object state as well as the intended address history. [6]
Keep the stop conditions in the migration record: unknown workspace identity, unverified mapping, an unexpected action, changed input values or an unexplained interface change. That record gives a later operator a concrete reason to hold the release without treating every warning as a new improvisation.
For remote infrastructure, combine this mapping review with the existing saved-plan approval guide. That guide binds approval to an artifact; this one establishes whether the artifact preserves the intended objects.
- Does switching to for_each automatically preserve existing instances?
- No. Numeric and keyed addresses differ. Describe the verified correspondence with move declarations and inspect the plan before execution. Stable keys help future inventory changes only after the current objects have been mapped correctly. [1][2][3]
- Can a moved resource still be replaced?
- Yes. An address move and a configuration change are separate concerns. A provider may require replacement for changed arguments. Preserve values during an identity-only stage and inspect both the address history and every planned action. [1][5]
- Should I delete moved blocks after one successful apply?
- Consider every supported consumer and upgrade path. A shared module can still have users with old state addresses. HashiCorp treats removing move declarations as a breaking change; one workspace's success does not establish everyone else's compatibility. [1]
- Does the built-in fixture prove my cloud migration is safe?
- No. It demonstrates Terraform addressing and local lifecycle behavior without a remote provider. Production needs its own state identity check, provider-specific argument review, current plan and controlled execution process. Keep the two evidence scopes separate. [4][6]