Terraform Advanced — count vs for_each
The definitive guide on when to use count and when to use for_each.
Use count For: On/Off Toggles
# ✅ count is perfect for conditional creation
resource "aws_cloudwatch_metric_alarm" "cpu" {
count = var.enable_alarms ? 1 : 0
# ...
}
# Access with one()
output "alarm_arn" {
value = one(aws_cloudwatch_metric_alarm.cpu[*].arn)
}
Use for_each For: Named Collections
# ✅ for_each gives stable, name-based keys
resource "aws_iam_user" "this" {
for_each = toset(["alice", "bob", "carol"])
name = each.value
}
# State: aws_iam_user.this["alice"], aws_iam_user.this["bob"]
# Removing "bob" only destroys bob — alice and carol are untouched
The count Reorder Problem
# ❌ With count: removing item 0 shifts everything
variable "users" {
default = ["alice", "bob", "carol"]
# Remove "alice" → bob becomes [0], carol becomes [1]
# Terraform destroys alice AND bob, recreates bob at [0]
}
resource "aws_iam_user" "this" {
count = length(var.users)
name = var.users[count.index]
}
⚠️ Warning: Never use
countwith a list that may have items removed from the middle.
Quick Rule
Need on/off? → count
Named collection? → for_each
List that may change? → for_each + toset()
What’s Next?
Master the lifecycle block.