Course contentsShow
← Cloud and Infrastructure
Lesson 815 of 2,98915. Terraform in PracticeFree lesson

Count vs For_Each: Choosing the Right Meta-Argument

Understand when to use count versus for_each for resource creation and the implications for state management.

Count vs For_Each: Choosing the Right Meta-Argument

What you'll learn: You'll discover how to decide between count and for_each when creating multiple resources, and why this choice matters for your infrastructure's stability.

The Core Decision

Both count and for_each let you create multiple instances of a resource, but they manage those instances very differently in Terraform's state. Think of count like organizing items by position in a numbered list (0, 1, 2...), while for_each is like organizing items by unique name tags.

When to Use Count

Use count when:

  • You need a specific number of identical resources
  • Order doesn't matter and resources are interchangeable
  • You're toggling a resource on/off with count = var.enabled ? 1 : 0
resource "aws_instance" "server" {
  count         = 3
  instance_type = "t2.micro"
  # Resources addressed as: aws_instance.server[0], [1], [2]
}

The problem: If you remove the middle item, Terraform re-indexes everything. Deleting server[1] makes server[2] become server[1]—triggering unnecessary resource destruction and recreation.

When to Use For_Each

Use for_each when:

  • Each resource represents a distinct, identifiable item
  • You might add/remove specific items from a set or map
  • Resource identity matters more than count
resource "aws_instance" "server" {
  for_each      = toset(["web", "api", "worker"])
  instance_type = "t2.micro"
  # Resources addressed as: aws_instance.server["web"], ["api"], ["worker"]
}

Removing "api" only destroys that one resource—no cascading changes.

The State Management Impact

count uses index-based addressing; adding or removing items mid-list reshuffles the state. for_each uses key-based addressing; each item has a stable identity regardless of additions or removals.

Key Takeaway: Use count for simple multipliers and conditional toggles; prefer for_each when managing collections of distinct resources that may change over time—it prevents unintended resource churn in your state.