Terraform interview question · Most asked

count or for_each: when do you use each?

Summary

Use for_each (over a map or set of strings) when creating several similar resources identified by meaningful keys; use count mainly for conditionally creating zero or one resource (count = var.enabled ? 1 : 0). for_each keys resources by name, so adding or removing one item does not affect the others.

Longer Answer

With count, resources are addressed by index (aws_s3_bucket.this[0]). Removing an item from the middle of a list shifts every later index, so Terraform plans to destroy and recreate resources that did not really change. With for_each, addresses are stable keys (aws_s3_bucket.this["logs"]). Keys must be known at plan time, so you cannot use values computed during apply (such as generated IDs) as keys.

Code Example

resource "aws_s3_bucket" "this" {
  for_each = toset(["logs", "assets", "backups"])
  bucket   = "acme-${each.key}-prod"
}

Key Points

  • for_each: stable keys for collections.
  • count: on/off toggles.
  • Removing from a count list shifts indexes.
  • for_each keys must be known at plan time.

More most-asked Terraform questions

← All Terraform questions