Interview Prep/Terraform/Resources Variables and Expressions

`for_each` fails because the map keys depend on a resource ID not known until apply. What's the fix?

IntermediateScenarioResources Variables and Expressions
Answer

Situation read → for_each keys must be known at plan time.

What I'd do →

  1. Key by static values such as names, not generated IDs.
  2. Put the unknown part in the value instead.
# bad:  for_each = toset(aws_subnet.this[*].id)
# good: keys are static names, IDs are values
for_each = { for k, v in aws_subnet.this : k => v.id }

Why → Terraform has to know how many instances exist and their addresses before applying; values can be unknown, keys cannot.

Interview tip → If you hit this, the root cause is usually using the wrong thing as the identity.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions