The keys come from something that does not exist yet
CommonThe for_each expression builds its keys from an attribute only the provider can supply after creation — a generated ID, an ARN, an IP address. During planning that value is unknown, so Terraform cannot name the instances. This is also why it fails on new environments and not old ones: once the source resource exists, its attribute is known from state and the same expression resolves, until a change forces that resource to be replaced and the attribute is unknown again.
Confirm
grep -n 'for_each' *.tf
A for_each whose collection is built from another resource's attribute — something like toset([aws_instance.web.id]) or a set from a data source that depends on a resource
Fix
- Key the collection by something you control in configuration, and move the apply-time value into the map's values: for_each = { primary = aws_instance.web.id }. Keys known, values free to be unknown.
- If the keys genuinely come from another resource, derive them from that resource's configuration rather than its outputs — the same list you used to create it, not the IDs it returned.
- The error suggests -target to apply the dependency first. HashiCorp's documentation says to use -target only in exceptional circumstances and not for routine operations, because it can lead to undetected configuration drift. It gets one environment past the error; it does not fix the configuration for the next empty state.
terraform plan
Re-plan after restructuring. Test against an empty state too — a new workspace — because existing state can hide the problem.