Terraform "Invalid for_each argument" depends on values known after apply in CI
for_each must know its keys at plan time. When the map or set comes from an attribute that is only known after another resource is created, Terraform cannot expand the instances and rejects the for_each.
What this error means
plan fails with "Error: Invalid for_each argument" and "the for_each value depends on resource attributes that cannot be determined until apply".
Error: Invalid for_each argument
on main.tf line 20, in resource "aws_route53_record" "rec":
20: for_each = { for s in aws_subnet.this : s.id => s }
The "for_each" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.Common causes
for_each keys come from a not-yet-created resource
Keying on an attribute like an id or arn that is computed at apply means the key set is unknown when the plan is built.
A chain of resources feeds the for_each
The set is derived from outputs of resources created in the same run, so their values are unknown at plan.
How to fix it
Key for_each on values known at plan time
- Build the for_each map from inputs or known keys, not computed attributes.
- Reference the computed attribute only inside the resource body.
- Re-run plan so the key set is static.
# key on the static var, look up the computed id inside the body
for_each = var.subnet_names
subnet_id = aws_subnet.this[each.key].idApply the upstream resources first if unavoidable
When keys genuinely cannot be known in advance, apply the resource that produces them with -target first, then apply the rest.
terraform apply -target=aws_subnet.thisHow to prevent it
- Derive for_each keys from variables or locals, not computed ids.
- Avoid feeding one resource's computed output into another's for_each.
- Reserve -target for bootstrapping, not routine applies.