HandsOnAzure

count vs for_each: The Index Trap That Recreates Your Infrastructure

Try it yourself: The index trap →

On this page
  1. Why count disturbs everything downstream
  2. Why for_each doesn’t
  3. The rule
  4. Migrating count to for_each without the carnage
  5. The mental model
  6. References

This one looks like a style preference and is actually a production incident waiting to happen.

You have a list of things to create (storage accounts, subnets, firewall rules), so you reach for count and a list. It works. Then one day you remove an item from the middle of that list, run plan, and Terraform proposes changes not just to that item, but to every item after it. When the attribute that differs cannot be changed in place, those changes are replacements: destroy, then create. On stateful resources, a replacement means data loss. On networking, it means an outage.

This is the index trap, and it is the single best reason to understand how count and for_each track state differently. The choice between them is not about taste. It is about what happens when the collection changes.

Why count disturbs everything downstream

count keys each resource in state by its numeric position: [0], [1], [2]. That index is the resource’s identity as far as Terraform is concerned.

variable "accounts" {
  default = ["alpha", "bravo", "charlie", "delta"]
}

resource "azurerm_storage_account" "this" {
  count = length(var.accounts)
  name  = "st${var.accounts[count.index]}example"
  # ...
}

State holds:

azurerm_storage_account.this[0]  ->  stalpha
azurerm_storage_account.this[1]  ->  stbravo
azurerm_storage_account.this[2]  ->  stcharlie
azurerm_storage_account.this[3]  ->  stdelta

Now remove "bravo" from the middle. The list becomes ["alpha", "charlie", "delta"] and the indices shift:

[0] -> stalpha     (unchanged)
[1] -> stcharlie   (was stbravo!)  -> destroy stbravo, recreate as stcharlie
[2] -> stdelta     (was stcharlie!) -> destroy stcharlie, recreate as stdelta
[3] -> (gone)      -> destroy stdelta

Terraform does not understand that you removed bravo. It sees that position [1] used to be stbravo and is now stcharlie. Everything from the removal point onward shifts up by one. In this example the plan reads 2 to add, 3 to destroy: two storage accounts are replaced ([1] and [2]) and the last one ([3]) is deleted. You removed one item from the list, and three resources are destroyed.

One caveat matters. The index shift is always there, but whether it ends in a replacement or in an in-place update depends on which attributes differ and on the provider. Here the storage account name comes from the list entry, and a storage account cannot be renamed in place, so each shifted instance is replaced. If only a tag or a size differed, the same shift would produce an update, not a destroy. The shift is the trap; replacement is what it becomes for attributes that force a new resource.

Why for_each doesn’t

for_each keys each resource by a stable map key or set value, not by position. Identity is the key, and keys don’t shift when other keys leave.

variable "accounts" {
  default = ["alpha", "bravo", "charlie", "delta"]
}

resource "azurerm_storage_account" "this" {
  for_each = toset(var.accounts)
  name     = "st${each.key}example"
  # ...
}

State holds:

azurerm_storage_account.this["alpha"]
azurerm_storage_account.this["bravo"]
azurerm_storage_account.this["charlie"]
azurerm_storage_account.this["delta"]

Remove "bravo" and the plan is exactly what you meant:

  # azurerm_storage_account.this["bravo"] will be destroyed

alpha, charlie, and delta are addressed by name, not position, so they are untouched. One removal, one destroy. This is the behaviour you almost always actually want.

The rule

Use for_each whenever the collection represents a set of distinct things with identity: named accounts, subnets, rules, users, regions. Which is to say: almost always.

Use count only for:

  • A genuine on/off toggle: count = var.enabled ? 1 : 0
  • N identical, interchangeable copies where position genuinely carries no meaning and the list only ever grows or shrinks at the end

If the elements have names, keys, or any identity you would recognise, use for_each. The test is simple: would removing a middle element be a normal operation? If yes, count will hurt you, and for_each is the answer.

Migrating count to for_each without the carnage

If you already have a count-based resource and want to switch, naively changing the code triggers the very destroy-and-recreate you are trying to avoid: Terraform sees this[0] disappear and this["alpha"] appear. Use moved blocks to remap the addresses with zero destruction:

moved {
  from = azurerm_storage_account.this[0]
  to   = azurerm_storage_account.this["alpha"]
}

moved {
  from = azurerm_storage_account.this[1]
  to   = azurerm_storage_account.this["bravo"]
}
# ...one per element

Run plan and confirm it shows moves only, no destroys. This converts the index-keyed state to identity-keyed state in place, in a reviewable PR. Do not delete the moved blocks right after your own apply. Keep them until every state and environment that uses this configuration has applied them: dev, test, production, and any other copy. If this is a reusable module that other teams consume, keep the history: HashiCorp recommends retaining historical moved blocks, because removing them is a breaking change. A configuration that still uses the old addresses will then plan to delete the existing objects instead of moving them. In a private configuration where you are certain everyone has applied the change, the blocks can be removed afterwards. (More on this technique in Refactoring Terraform State Without Destroying Everything.)

The mental model

count says “make N of these, numbered by position.” for_each says “make one of these per named thing.” Infrastructure is almost never genuinely positional; your subnets and storage accounts have identities, not seat numbers. Default to for_each, keep count for the boolean toggle, and the index trap simply never happens to you. The day someone removes an item from the middle of a list, the difference between a one-line plan and a production incident is which one you reached for.

References