Search code examples
amazon-web-servicesterraformterraform-provider-aws

Terraform - if within for_each. Can I filter for_each?


With the following I can loop through a resource block to add route table associations to "all" of my subnets easily. However I need to create associations only for my public subnets.

How can I make this "if" statement work? Or any other way to filter on each.value.class == "pub" for that matter.

resource "aws_route_table_association" "rtb-pub" {
  for_each =  local.subnets_map 
  if each.value.class == "pub"    ## <---- how?

  route_table_id = aws_route_table.rtb-pub.id
  subnet_id      = aws_subnet.map["${each.value.subnet}"].id
}

Thanks in advance!


Solution

  • It depends on exactly what is the structure of your local.subnets_map. But the for_each should be something like the following one:

    resource "aws_route_table_association" "rtb-pub" {
    
      for_each =  {for key, val in local.subnets_map: 
                   key => val if val.class == "pub"}
    
      route_table_id = aws_route_table.rtb-pub.id
      subnet_id      = aws_subnet.map["${each.value.subnet}"].id
    }