What is the difference between count and for_each in Terraform?
Both count and for_each are Terraform meta-arguments that allow you to create multiple instances of a resource from a single resource block, but they work differently and have important trade-offs.
count
count creates resources by index (0, 1, 2, …). Resources are addressed as resource_type.name[index].
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-${count.index}"
}
}
# Reference: aws_instance.web[0], aws_instance.web[1], aws_instance.web[2]count Problem: Index-based destruction
If you delete element at index 1 from a list of 3, Terraform destroys index 1 AND recreates index 2 as the new index 1. This causes unnecessary resource churn.
for_each
for_each creates resources from a map or set of strings. Resources are addressed by their key.
# Using a set
resource "aws_iam_user" "users" {
for_each = toset(["alice", "bob", "carol"])
name = each.key
}
# Using a map
resource "aws_instance" "web" {
for_each = {
prod = "t3.medium"
dev = "t3.small"
}
ami = "ami-0c55b159cbfafe1f0"
instance_type = each.value
tags = {
Name = "web-${each.key}"
}
}
# Reference: aws_instance.web["prod"], aws_instance.web["dev"]for_each Advantage: Key-based stability
Deleting “bob” from the list only destroys bob’s resource. Alice and Carol are unaffected.
Comparison
| Feature | count | for_each |
|---|---|---|
| Addressing | By index [0,1,2] | By key [“name”] |
| Input type | Number | Map or Set |
| Deletion behavior | Index shift causes recreation | Key-based, stable |
| Dynamic values | Can’t use unknown at plan time | Map values must be known |
| Best for | Identical resources | Resources with different configs |
When to Use Each
Use count when:
- Creating identical resources (e.g., N identical EC2 instances)
- The total count is determined by a simple number
- Resources don’t need stable identity
Use for_each when:
- Creating resources with different configurations
- Working with a list/map of named resources
- Stability of individual resources is important (prevents unnecessary destruction)