A module uses for_each = toset(aws_subnet.private[*].id) to create route table associations. On a fresh environment, the plan fails with an error that for_each has dependencies that cannot be determined before apply. What is the best fix?
Select an answer to reveal the explanation.
Short Explanation
for_each needs its list of keys before the party starts, and subnet IDs don't exist until the subnets do. So you key on something you already know, like the names, and look up the IDs inside the resource. The trap is depends_on, which changes ordering but can't make an unknown value known.
Full Explanation
Terraform must know every for_each key during planning, because each key becomes part of a resource instance address. The documentation states that all values for_each iterates over must be known before Terraform performs remote operations; otherwise Terraform reports that for_each has dependencies that cannot be determined before apply. Subnet IDs are assigned by the provider when the subnets are created, so on a fresh environment they are unknown at plan time. The reliable fix is to key the collection on values known from configuration, for example the same map of subnet names or availability zones that created the subnets, and reference the corresponding subnet ID inside the resource arguments, where unknown values are allowed. Converting the IDs into a map does not change their unknown status; the keys would still be unknown. Adding depends_on only affects ordering and does not make values known during planning; it can even make more values unknown. Moving the expression into a local value changes nothing, because a local is evaluated from the same references and stays unknown until the subnets exist. Exam caveat: the -target workaround the error message mentions is for exceptional recovery, not a design fix. Operational check: rewrite the expression, run a plan in an empty environment, and confirm the association addresses use the subnet names as keys.