Terraform addresses every instance created by for_each using its map or set key. A key is part of resource identity in state, so changing it can appear as a removal and a creation even when the intended remote object is unchanged. The collection keys must be known before remote actions. By contrast, count uses numeric indexes: inserting one item near the front of an ordered list can shift several addresses and produce noisy or dangerous plans.
Terraform collection keys: keep resource identity stable through reorderings
Operational decision
A receipt platform has worker groups for eastern and western regions. Model each with a stable region code as the map key, then review a plan after reordering the source declaration: it should not replace groups simply because the file order changed. The fragment uses a map of approved group sizes; in a complete module, each key feeds a resource that has unique names and subnet choices. Do not derive the key from a provider-generated ID that is unknown until apply, and do not place secret data in keys because addresses appear in output and state metadata. When a business key genuinely changes, write an explicit state address move and inspect the resulting plan before apply. Test additions, deletions, and renames separately; a rename may require a remote rename or replacement even when the state address is moved.
locals {
receipt_worker_groups = {
"region-east" = 3
"region-west" = 2
}
}
resource "terraform_data" "worker_group_contract" {
for_each = local.receipt_worker_groups
input = {
region_code = each.key
target_size = each.value
}
}Cost and verification
A stable key prevents address churn, but it does not make provider updates free. Each instance still incurs refresh and possible API calls, and a large collection expands plan size roughly with instance count. Key design also creates migration cost if a team later changes its naming scheme. Measure planned creates and destroys after each collection edit, not just total instance count. Prefer a key based on a durable identifier that operators can recognize during incident response.
Common Mistakes
- Do not use a provider-generated ID as a for_each key before it exists.
- Do not put credentials or private customer fields in instance keys.
- Do not equate an address move with a remote rename.
Connected lessons
- DevOps: delivery, infrastructure, and reliable operations
- Terraform address refactoring: move state without recreating infrastructure
- Terraform modules: small interfaces and explicit state owners
- Terraform state: shared ownership and safe plans
- Ephemeral environments: keep preview access and cost bounded
