A practitioner defines a variable to hold two Availability Zones and iterates over it with for_each to create one subnet per zone. When they run terraform plan, Terraform reports that for_each cannot be used with this value. What change to the variable makes for_each work directly?
variable "azs" {
type = list(string)
default = ["eu-west-1a", "eu-west-1b"]
}
resource "aws_subnet" "this" {
for_each = var.azs
availability_zone = each.value
}- AChange the variable type to tuple([string, string]), because a fixed-length tuple is the collection for_each expects.
- BChange the variable type to set(string), because for_each accepts a map or a set of strings, not a list. Correct
- CLeave the type as list(string) and add a lifecycle block with create_before_destroy set to true.
- DLeave the type as list(string) and reference each.key instead of each.value in the resource.
Why A is wrong: A tuple looks like an ordered pair that might suit two zones, but for_each rejects tuples just as it rejects lists; it needs a map or a set.
Why B is correct: for_each requires a map or a set of strings; converting the list to a set of strings gives it a collection it can key by value, so it works directly.
Why C is wrong: create_before_destroy governs replacement ordering and does nothing about the for_each input type, so the plan would fail with the same error.
Why D is wrong: Swapping each.key for each.value does not change that a raw list is an invalid for_each argument, so Terraform still refuses the list.