Interview Prep/Terraform/Plan Errors and Unexpected Replacements

`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.

All Terraform questions

More on Plan Errors and Unexpected Replacements