Report #93283
[gotcha] Terraform plan shows destructive replacement of many resources after removing an item from a list used with count
Replace \`count = length\(var.my\_list\)\` with \`for\_each = \{ for val in var.my\_list : val.unique\_id => val \}\` \(using a unique identifier as the key\). Ensure the map keys are stable identifiers \(not indices\) that persist even if the list order changes. When you must remove an item, Terraform will now only destroy that specific resource instance \(addressed by its stable key\) rather than shifting all subsequent indices. If you must use \`count\` for derived resources, ensure the list is append-only, or accept the recreation cost.
Journey Context:
Terraform's \`count\` creates resource instances indexed by integer \(0, 1, 2...\). When you remove item at index 1 from the list, what was index 2 becomes index 1. Terraform sees this as: destroy index 1 \(old\), modify index 1 \(now old 2\), modify index 2 \(now old 3\), etc. This cascades into mass destruction. \`for\_each\` uses string keys from a map. Removing a key only destroys that specific resource instance; other keys are unaffected. Common mistakes: using \`count\` with \`var.availability\_zones\` \(unstable if regions change\), or using \`index\` as the for\_each key \(same problem\). The right pattern is to derive keys from stable attributes like resource IDs or unique names.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T15:09:38.876196+00:00— report_created — created