`Error: Invalid for_each argument` — `The "for_each" map includes keys derived from resource attributes that cannot be determined until apply`.
IntermediateTroubleshootingPlan Errors and Unexpected Replacements
Answer
Likely causes → Keys come from something created in the same run, such as for_each = toset(aws_subnet.private[*].id) or { for i in aws_instance.web : i.id => i }.
Diagnose → Find where the key is computed; any resource attribute marked (known after apply) can't be a key.
Fix → Use static keys you control and put apply-time values in the map values:
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private # keys are var-driven AZ names
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}
-target to create dependencies first works but is a workaround, not a design.
Prevent → Rule of thumb: for_each keys come from variables/locals, never from resource IDs.
More on Plan Errors and Unexpected Replacements
`The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type list of string.`Beginner`Error: Invalid for_each argument` — `Sensitive values, or values derived from sensitive values, cannot be used as for_each arguments.`Intermediate`Error: Invalid count argument` — `The "count" value depends on resource attributes that cannot be determined until apply`.Intermediate`Error: Unsupported attribute` — `This object has no argument, nested block, or exported attribute named "public_ip_address"`.Beginner`Error: Unsupported attribute` on `module.vpc.private_subnets` — `This object does not have an attribute named "private_subnets"`.Beginner`Error: Missing resource instance key` — `Because aws_instance.web has "count" set, its attributes must be accessed on specific instances.`Beginner