For_each vs Count: Choosing the Right One
The choice between for_each
and count
is one of the most common sources of confusion in Terraform, accounting for approximately 20-25% of all code organization questions.
The Problem
# Using count (PROBLEMATIC APPROACH)
resource "aws_instance" "server" {
count = length(var.server_names)
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = var.server_names[count.index]
}
}
When using count
, removing an item from the middle of var.server_names
causes Terraform to recreate all subsequent resources due to index shifting.
The Solution
# Using for_each (BETTER APPROACH)
resource "aws_instance" "server" {
for_each = toset(var.server_names)
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = each.key
}
}
Using for_each
creates stable, named identifiers, preventing the dreaded "index shifting" problem. Platforms like Scalr make it easier to visualize and manage these resources with clear dependency graphs, showing exactly which resources will be affected by changes.