Home > OS >  Filtering variables map list
Filtering variables map list

Time:09-30

I have a data structure and I need to extract a list out of a map of lists based on the maps key. Here is the sample data:

locals {
  firwall_rules = ["first", "third"]   # this is the filter used on firewall_rules_lookup 
  firewall_rules_lookup = {
    type = map
    "first" = [ { name ="rule1.1", start_ip="0.0.0.1" , end_ip = "0.0.0.2" },
                { name ="rule1.2", start_ip="0.0.0.4" , end_ip = "0.0.0.5" },
              ],
 
    "second"= [ { name ="rule2.1", start_ip="0.0.1.1" , end_ip = "0.0.1.2" } ],
 
    "third" = [ { name ="rule3.1", start_ip="0.0.3.1" , end_ip = "0.0.3.2" },
                { name ="rule3.2", start_ip="0.0.3.4" , end_ip = "0.0.3.5" },
              ]
  }
  
  fw_rules = flatten([
    for rule_name in local.firewall_rules : {
      for r in local.firewall_rules_lookup[rule_name] : {
         name = r.name
         start_ip = r.start_ip
         end_ip = r.end_ip
      }
    }
  ])
}

Expected result:

fw_rules=
[ { name ="rule1.1", start_ip="0.0.0.1" , end_ip = "0.0.0.2" },
  { name ="rule1.2", start_ip="0.0.0.4" , end_ip = "0.0.0.5" },
  { name ="rule3.1", start_ip="0.0.3.1" , end_ip = "0.0.3.2" },
  { name ="rule3.2", start_ip="0.0.3.4" , end_ip = "0.0.3.5" }
]

The inner for loop is not working. Terraform gives me an error. I think the for loops work only with maps. Is there a different solution to this problem?

CodePudding user response:

It should be as follows:

locals {
  firewall_rules = ["first", "third"]   # this is the filter used on firewall_rules_lookup 
  firewall_rules_lookup = {
    "first" = [ { name ="rule1.1", start_ip="0.0.0.1" , end_ip = "0.0.0.2" },
                { name ="rule1.2", start_ip="0.0.0.4" , end_ip = "0.0.0.5" },
              ],
 
    "second"= [ { name ="rule2.1", start_ip="0.0.1.1" , end_ip = "0.0.1.2" } ],
 
    "third" = [ { name ="rule3.1", start_ip="0.0.3.1" , end_ip = "0.0.3.2" },
                { name ="rule3.2", start_ip="0.0.3.4" , end_ip = "0.0.3.5" },
              ]
  }
  
  fw_rules = flatten([
    for rule_name in local.firewall_rules : [
      for r in local.firewall_rules_lookup[rule_name] : {
         name = r.name
         start_ip = r.start_ip
         end_ip = r.end_ip
      }
    ]
  ])
}
  • Related