How do you loop over nested structures, for example subnets per VPC?
AdvancedConceptLoops, Conditionals, Dynamic Blocks and Functions
Answer
Flatten into a single list of objects with unique keys, then for_each over it.
locals {
subnets = flatten([
for vpc_k, vpc in var.vpcs : [
for s in vpc.subnets : { key = "${vpc_k}-${s.name}", vpc = vpc_k, cidr = s.cidr }
]
])
}
resource "aws_subnet" "s" {
for_each = { for s in local.subnets : s.key => s }
vpc_id = aws_vpc.v[each.value.vpc].id
cidr_block = each.value.cidr
}
More on Loops, Conditionals, Dynamic Blocks and Functions
How does `count` work?BeginnerHow does `for_each` work?BeginnerWhen should you choose `for_each` over `count`?IntermediateHow do you use `for_each` with a list of objects?IntermediateWhat does "The for_each value depends on resource attributes that cannot be determined until apply" mean?AdvancedHow do you create a resource conditionally?Beginner