This site contains affiliate links and we may earn a commission at no extra cost to you. Learn more.

Terraform count vs for_each explained (with examples)

Updated September 6, 2026

When to use count vs for_each in Terraform, why for_each is usually the safer choice, and how it maps to a common Terraform Associate 004 exam topic.

Both count and for_each create multiple instances of a resource or module from a single block, and the exam expects you to know when each is appropriate. The short version: reach for for_each by default, and use count for simple numeric duplication or conditional creation.

count: index-based

count takes a whole number and creates that many instances, addressed by position: aws_instance.web[0], [1], and so on. It is perfect for "make N identical things" and for the conditional pattern count = var.enabled ? 1 : 0.

The catch is that instances are tied to their index. Remove the first item from the list that drives count and every later item shifts down one index, so Terraform plans to destroy and recreate resources that only moved position.

for_each: key-based

for_each iterates over a map or a set of strings and addresses each instance by a stable key: aws_instance.web["api"]. Because each instance is bound to a key rather than a position, adding or removing one item only affects that item — the others stay put. That stability is why for_each is the safer default for anything you will edit over time.

Which to use

  • Use count for simple numeric duplication of identical resources, or for conditional creation (0 or 1).
  • Use for_each when instances are distinct, come from a map/set, or when the collection will change over time.
  • Both work on module blocks too, not just resources.

Exam tips

Expect a scenario that asks what happens when you remove an item from a count list (answer: index shift and recreation) versus a for_each map (answer: only that key is affected). Know that for_each needs a map or set of strings, and that you cannot use both count and for_each on the same block. Reinforce it in the 004 study plan.

Ready to start studying?

Related guides