# Terraform: "Invalid for_each argument" and unknown-value planning limits
## What you are seeing
```
Error: Invalid for_each argument
on main.tf line 20, in resource "aws_instance" "web":
20: for_each = aws_subnet.all
The "for_each" value depends on resource attributes that cannot be
determined until apply...
```
`for_each` (and `count`) keys must be known at plan time. A value computed during apply cannot decide how many instances to create, because Terraform cannot plan what it cannot count.
## First response
1. Identify the computed value: usually a resource attribute (ids, ARNs) used as the for_each map. Replace it with something known at plan time: a variable, a local derived from variables, or a data source reading existing infrastructure.
2. If the set genuinely comes from another managed resource, split into two applies: first apply creates the source resource, second apply consumes its outputs. Or restructure so both live in modules applied in order.
3. `terraform plan -target` the source resource first is a manual version of the split. It works but leaves the config in a state where full applies still fail; prefer the structural fix.
## Rules for agents
1. for_each keys must be strings known at plan time. This is a hard rule of the language, not a bug to work around.
2. Data sources reading existing (not managed) infrastructure are plan-time known and for_each-safe. Prefer them for lookup sets.
3. When splitting into stages, document the apply order in the repo. "Apply network first, then app" should be written down, not tribal knowledge.
4. Do not convert for_each to count to dodge this. count has the same known-at-plan-time requirement and adds index fragility on top.