I have this structure in a terraform output:
"eks_private_subnets_in_zones": {
"value": {
"us-east-1a": [
"subnet-11111111111111111",
"subnet-22222222222222222"
],
"us-east-1b": [
"subnet-33333333333333333",
"subnet-44444444444444444"
],
"us-east-1c": [
"subnet-55555555555555555",
"subnet-66666666666666666"
]
},
How can I produce a list of subnets, which are one of the subnets (say, the first one) from each AZ? To be clear, I want:
["subnet-111111111111111111", "subnet-33333333333333333", "subnet-55555555555555555"]
I tried
{for az in eks_private_subnets_in_zones: subnet.id => az[0]}
But I'm completely lost here
I would use the values function:
output "first_subnet_in_each_availability_zone" {
value = [for subnet_list in values(eks_private_subnets_in_zones.value) : subnet_list[0]]
}
This code snippet does the following:
It iterates over the values of the eks_private_subnets_in_zones.value map, which are lists of subnet IDs.
For each list subnet_list
it takes the first element subnet_list[0]
, which corresponds to the first subnet in each availability zone.
It constructs a new list of these first subnet IDs and assigns it to the output named first_subnet_in_each_availability_zone.
After applying this configuration with terraform apply, the output first_subnet_in_each_availability_zone will contain the list of the first subnet from each availability zone as requested:
["subnet-11111111111111111", "subnet-33333333333333333", "subnet-55555555555555555"]
The for expression is documented in detail in the Terraform language documentation. Additionally, This is an example of using for expressions to manipulate collections. For further insights into loops and other control structures in Terraform you might find the article Terraform tips & tricks: loops, if-statements, and gotchas by Yevgeniy Brikman helpful.