for_each vs count in Terraform

Both meta-arguments create multiple instances of a resource or module from one block. They differ in how each instance is identified in state, and that difference determines how safely the configuration handles change.

Behavior

count takes a whole number and creates that many instances, addressed by integer index. count.index is available inside the block.

resource "aws_instance" "web" {
  count         = length(var.names)
  ami           = var.ami
  instance_type = "t3.small"
  tags          = { Name = var.names[count.index] }
}
# state addresses: aws_instance.web[0], aws_instance.web[1], ...

for_each takes a map or a set of strings and creates one instance per element, addressed by key. each.key and each.value are available inside the block. For a set, both are the same string.

locals {
  servers = {
    api    = "t3.small"
    worker = "t3.medium"
  }
}

resource "aws_instance" "web" {
  for_each      = local.servers
  ami           = var.ami
  instance_type = each.value
  tags          = { Name = each.key }
}
# state addresses: aws_instance.web["api"], aws_instance.web["worker"]

A single block cannot use both arguments.

Index shifting with count

Because count identifies instances by position, removing an element from the middle of a list renumbers every element after it. Given ["api", "worker", "cron"], removing "worker" produces:

aws_instance.web[1]  ~ update in-place   (Name: "worker" -> "cron")
aws_instance.web[2]  - destroy

Terraform does not remove the worker instance. It reconfigures instance 1 to be cron and destroys the original cron. If the changed argument forces replacement (for example ami or subnet_id), instance 1 is destroyed and recreated as well. With a dozen elements and an edit near the front, most of the collection is affected.

With for_each, removing the worker key destroys only aws_instance.web["worker"]. Other instances keep their addresses and are untouched.

Constraints on for_each

count must also be known at plan time, but it only needs a number, so it fails less often. The typical for_each failure is building keys from attributes of a resource created in the same apply:

# Error: The "for_each" set includes values derived from resource
# attributes that cannot be determined until apply
resource "aws_route_table_association" "private" {
  for_each       = toset(aws_subnet.private[*].id)
  subnet_id      = each.value
  route_table_id = aws_route_table.private.id
}

Subnet IDs are unknown until the subnets exist. Key the loop on something known, such as the keys of the upstream for_each resource:

resource "aws_route_table_association" "private" {
  for_each       = aws_subnet.private   # map keyed by the subnets' own for_each keys
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private.id
}

Conditional creation

For an optional resource, count with a 0 or 1 value is the idiomatic form:

resource "aws_s3_bucket" "logs" {
  count  = var.enable_logging ? 1 : 0
  bucket = "${var.name}-logs"
}

output "logs_bucket" {
  value = one(aws_s3_bucket.logs[*].id)   # null when count = 0
}

for_each can do the same with an empty collection (var.enabled ? { main = true } : {}), but the result is no clearer, and references then need a key. Use count for toggles.

Referencing instances

countfor_each
Inputwhole numbermap or set of strings
Iteratorcount.indexeach.key, each.value
Instance addressweb[0]web["api"]
Remove one itemlater indexes shiftonly that key is affected
Single instanceweb[0].idweb["api"].id
All instancesweb[*].idvalues(web)[*].id, or a for expression
Optional resource0 or 1empty map or set
Dynamic blocksnot supportedthe only iteration argument (dynamic uses for_each)

for_each resources are objects keyed by instance key, so { for k, v in aws_instance.web : k => v.private_ip } yields a map you can pass straight to an output or another resource.

Migrating from count to for_each

Changing the argument alone makes Terraform destroy the indexed instances and create new keyed ones. Use moved blocks (Terraform 1.1+) to rewrite the state addresses instead:

moved {
  from = aws_instance.web[0]
  to   = aws_instance.web["api"]
}

moved {
  from = aws_instance.web[1]
  to   = aws_instance.web["worker"]
}

Run terraform plan and confirm it reports the moves and no create or destroy actions before applying. On older versions, use terraform state mv with the same addresses.

Choosing