for_each vs count in Terraform
Both meta-arguments create multiple instances of a resource or module from one block. They differ in how each instance is identified in state, and that difference determines how safely the configuration handles change.
Behavior
count takes a whole number and creates that many instances, addressed by integer index. count.index is available inside the block.
resource "aws_instance" "web" {
count = length(var.names)
ami = var.ami
instance_type = "t3.small"
tags = { Name = var.names[count.index] }
}
# state addresses: aws_instance.web[0], aws_instance.web[1], ...
for_each takes a map or a set of strings and creates one instance per element, addressed by key. each.key and each.value are available inside the block. For a set, both are the same string.
locals {
servers = {
api = "t3.small"
worker = "t3.medium"
}
}
resource "aws_instance" "web" {
for_each = local.servers
ami = var.ami
instance_type = each.value
tags = { Name = each.key }
}
# state addresses: aws_instance.web["api"], aws_instance.web["worker"]
A single block cannot use both arguments.
Index shifting with count
Because count identifies instances by position, removing an element from the middle of a list renumbers every element after it. Given ["api", "worker", "cron"], removing "worker" produces:
aws_instance.web[1] ~ update in-place (Name: "worker" -> "cron")
aws_instance.web[2] - destroy
Terraform does not remove the worker instance. It reconfigures instance 1 to be cron and destroys the original cron. If the changed argument forces replacement (for example ami or subnet_id), instance 1 is destroyed and recreated as well. With a dozen elements and an edit near the front, most of the collection is affected.
With for_each, removing the worker key destroys only aws_instance.web["worker"]. Other instances keep their addresses and are untouched.
Constraints on for_each
- Input must be a map or a set of strings. A list must be converted with
toset(), which drops duplicates, or reshaped into a map with aforexpression. - The keys must be known at plan time. Values may be unknown.
- Sensitive values, or values derived from them, cannot be used as the
for_eachargument.
count must also be known at plan time, but it only needs a number, so it fails less often. The typical for_each failure is building keys from attributes of a resource created in the same apply:
# Error: The "for_each" set includes values derived from resource
# attributes that cannot be determined until apply
resource "aws_route_table_association" "private" {
for_each = toset(aws_subnet.private[*].id)
subnet_id = each.value
route_table_id = aws_route_table.private.id
}
Subnet IDs are unknown until the subnets exist. Key the loop on something known, such as the keys of the upstream for_each resource:
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private # map keyed by the subnets' own for_each keys
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}
Conditional creation
For an optional resource, count with a 0 or 1 value is the idiomatic form:
resource "aws_s3_bucket" "logs" {
count = var.enable_logging ? 1 : 0
bucket = "${var.name}-logs"
}
output "logs_bucket" {
value = one(aws_s3_bucket.logs[*].id) # null when count = 0
}
for_each can do the same with an empty collection (var.enabled ? { main = true } : {}), but the result is no clearer, and references then need a key. Use count for toggles.
Referencing instances
count | for_each | |
|---|---|---|
| Input | whole number | map or set of strings |
| Iterator | count.index | each.key, each.value |
| Instance address | web[0] | web["api"] |
| Remove one item | later indexes shift | only that key is affected |
| Single instance | web[0].id | web["api"].id |
| All instances | web[*].id | values(web)[*].id, or a for expression |
| Optional resource | 0 or 1 | empty map or set |
| Dynamic blocks | not supported | the only iteration argument (dynamic uses for_each) |
for_each resources are objects keyed by instance key, so { for k, v in aws_instance.web : k => v.private_ip } yields a map you can pass straight to an output or another resource.
Migrating from count to for_each
Changing the argument alone makes Terraform destroy the indexed instances and create new keyed ones. Use moved blocks (Terraform 1.1+) to rewrite the state addresses instead:
moved {
from = aws_instance.web[0]
to = aws_instance.web["api"]
}
moved {
from = aws_instance.web[1]
to = aws_instance.web["worker"]
}
Run terraform plan and confirm it reports the moves and no create or destroy actions before applying. On older versions, use terraform state mv with the same addresses.
Choosing
- Use
countfor a 0/1 toggle, or for a fixed number of interchangeable instances that nothing refers to individually. - Use
for_eachwhenever instances have identities, when they come from a collection that can change, or when they differ in configuration. - Prefer a map over a set when each instance needs more than a name; the values carry per-instance settings.
- If you are indexing into a list with
count.indexto look up per-instance settings, convert the list to a map and usefor_each.