When do you use count vs for_each in Terraform?
⚡
Quick Answer
count creates N indexed copies; for_each creates keyed instances from a map/set, which is stabler when items change.
Detailed Answer
count is fine for identical N copies but reindexes when you remove a middle element, causing churn. for_each keys resources by a stable identifier, so adding/removing one doesn't disturb the others. Prefer for_each for sets of named resources.
Code Example
resource "aws_iam_user" "u" {
for_each = toset(["alice","bob"])
name = each.key
}💡
Interview Tip
for_each avoids the reindex-churn problem of count.
terraformcountfor-each