RMDev
RMDev

Reputation: 73

Terraform - Iterate through map of maps depending on value of internal map

i'm trying to create a resource depending on a value of the internal map of a map. If that specific value is true then create the resource

Please find below the code:

variable "ip_restrictions" {
  type        = map(map(string))
  default = {
    test01 = {
      name                      = "test01"
      start_ip_address          = "0.0.0.0"
      end_ip_address            = "0.0.0.0"
      is_firewall               = false
    },
    test02 = {
      name                      = "test02"
      start_ip_address          = "0.0.0.0"
      end_ip_address            = "0.0.0.0"
      is_firewall               = true
    }
  }
}

resource "azurerm_sql_firewall_rule" "sql_firewall_rules" {
  for_each = {
    for restr in var.ip_restrictions :
    restr => restr
    if restr.is_firewall == true
  }
  
  name                = each.value.name
  resource_group_name = azurerm_resource_group.rg.name
  server_name         = azurerm_sql_server.sqls.name
  start_ip_address    = each.value.start_ip_address
  end_ip_address      = each.value.end_ip_address
}

Upvotes: 6

Views: 11565

Answers (2)

Cloudkollektiv
Cloudkollektiv

Reputation: 14699

Since your var.ip_restrictions is a map and not a list, you need to iterate over it like a map (returning a key and value). The shortest possible way in your situation:

for_each = {
  for key, restr in var.ip_restrictions :
    key => restr if restr.is_firewall
}

Gives:

"test02" = {
  "end_ip_address"   = "0.0.0.0"
  "is_firewall"      = "true"
  "name"             = "test02"
  "start_ip_address" = "0.0.0.0"
}

Upvotes: 3

Marcin
Marcin

Reputation: 238209

The correct form of your for_each should be:

  for_each = {
    for key, restr in var.ip_restrictions :
      key => restr if restr.is_firewall == "true"
  }

This will filter out all records with is_firewall of false.

Upvotes: 7

Related Questions