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
- How do you handle secrets in Terraform?
- A terraform plan wants to destroy and recreate a database. What do you do?
- What is Terraform, and how does it work at a high level?
- What is Terraform state, why is it needed, and where should it be stored?
- Walk through terraform init, plan and apply. What does each do?
- How would you run Terraform in CI/CD?
- What are Terraform modules, and how do you design good ones?
- How do you bring existing infrastructure under Terraform management?