`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 →
- Key by static values such as names, not generated IDs.
- 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.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced