Full lesson
Explore the full explanation, examples, and visuals at your own pace.
main.tf (count version)
Delete web from this list, and Terraform's plan suddenly wants to touch api and worker too. Why? Look at count.index in the tags line. It's the only link between a list item and a server, so the servers are tied to positions, not names.
variable "servers" {
default = ["web", "api", "worker"]
}
resource "aws_instance" "server" {
count = length(var.servers)
ami = var.ami_id
instance_type = "t3.micro"
tags = { Name = var.servers[count.index] }
}State remembers positions, not names
State tracks server zero, one, and two. Delete web, and everything slides up: zero becomes api, one becomes worker, and server two vanishes.
Your intent vs Terraform's plan
What you meant: destroy web, keep api and worker. What plan does: server[0] and server[1] get replaced with api and worker, and server[2], the real worker, gets destroyed. Replace happens when the changed attribute forces a new resource; otherwise it'd be an in-place update.
main.tf (for_each version)
The fix is for_each over toset of var.servers. Terraform now gives each instance a key instead of a position, and each.key replaces count.index for the Name tag. So the addresses become server web, server api, and server worker, names that don't shift when the list changes.
variable "servers" {
default = ["web", "api", "worker"]
}
resource "aws_instance" "server" {
for_each = toset(var.servers)
ami = var.ami_id
instance_type = "t3.micro"
tags = { Name = each.key }
}Now removing web touches only web
Delete web from the list, and only the web key disappears. API and worker keep their addresses, so the plan shows a single destroy.
moves.tf (Terraform 1.1+)
Here's the gotcha. Switching from count to for_each changes every address, so Terraform would destroy and recreate all three servers. Each moved block tells it that an old index, like zero, is now the key web, so state gets renamed. On older versions, terraform state mv does the same.
moved {
from = aws_instance.server[0]
to = aws_instance.server["web"]
}
moved {
from = aws_instance.server[1]
to = aws_instance.server["api"]
}
moved {
from = aws_instance.server[2]
to = aws_instance.server["worker"]
}When count is still fine
count still earns its place when items are interchangeable copies, or when you just need an on/off toggle, like count equals one or zero. Lists you only append to are safe too. Once items have distinct identities, use for_each.
- Identical copies, no per-item identity
- On/off toggle: count = 1 or 0
- Lists you only ever append to
count names servers by position; for_each names them by key.
count names servers by position; for_each names them by key. That's why removing web shifts everything under count, but touches only server["web"] under for_each. Before you apply any change to a count-based list, read the plan and check for indexes that shifted, because those show up as replacements.