Terraform · Infrastructure as code
When should you use count versus for_each?
Short answer
count creates instances by index; for_each creates them by stable keys. Prefer for_each for collections so removing an item does not shift indexes and force unrelated replacements.
Both meta-arguments create multiple instances of one resource block. count gives each instance a numeric index, while for_each uses a map or set key. The address format differs: aws_instance.web[0] versus aws_instance.web["api"].
resource "aws_iam_user" "team" {
for_each = toset(["asha", "ravi", "mei"])
name = each.value
}resource "aws_instance" "web" {
count = var.enabled ? 2 : 0
ami = data.aws_ami.base.id
instance_type = "t3.micro"
}Trade-offs
- count indexes shift when an item is removed from the middle
- for_each keys are stable and survive reordering
- count is concise for booleans and fixed replicas
- for_each requires a map or set of known keys at plan time
- Neither handles keys that are unknown until apply
Use count when the instances are interchangeable and the index has no meaning beyond position. Use for_each when each instance represents a named entity, such as a user, subnet or bucket. Do not build a for_each over a list; convert it to a map or set so keys are stable.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does removing an item from a count list cause churn?
- 2Can for_each iterate over a list?
- 3What happens when for_each keys are unknown at plan time?
- 4How do you migrate from count to for_each safely?
Say it in the interview
count gives instances numeric addresses, while for_each gives them stable keys. I prefer for_each for named collections, because deleting an item from the middle of a count list shifts every later index and can replace unrelated resources. count is still fine for a boolean toggle or a fixed number of identical replicas. Either way, changing the meta-argument changes addresses, so I plan a state migration.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.