A module takes variable buckets of type list(string) and a resource uses for_each = var.buckets. terraform plan fails because for_each received a list. What is the correct fix?
Select an answer to reveal the explanation.
Short Explanation
for_each wants name tags, not seat numbers. A list is all about position, so you convert it to a set and each bucket name becomes its own key. The trap is trying to keep the positions, which is exactly what for_each is built to avoid.
Full Explanation
The for_each meta-argument accepts a map or a set of strings, because each instance must have a stable, unique key. A list is ordered by position and may contain duplicates, so Terraform rejects it rather than guess at keys. Wrapping the value in toset() converts the list to a set of strings, removes any duplicates, and makes each bucket name the instance key, for example aws_s3_bucket.this["logs"]. Inside the block, each.key and each.value both hold the name. A tuple is also a positional sequence and is rejected for the same reason. A number from length() is what count expects; for_each does not accept a number. count.index is available only in resources that use count and cannot be combined with each.value in a for_each block. Exam caveat: converting a list with toset() loses ordering, so do not rely on element order inside the block, and ensure the strings are known at plan time. Operational check: after the change, run terraform plan and confirm the instance addresses are keyed by bucket name rather than by number, then run terraform state list after apply.