For_each with an extra condition

I’m looking for something familiar. I want to create multiple subnets and for each subnet i want to create a nsg, but for some subnets I don’t want to create the nsg. so i have this:

subnet = {
    subnet1= {
      cidrsubnet = "10.10.1.0/24"
      create_nsg = true
    },
    subnet2= {
      cidrsubnet = "10.10.2.0/24"
      create_nsg = true
    },
    subnet3= {
      cidrsubnet = "10.10.3.0/24"
      create_nsg = false
    }
  }

Now for each subnet there will be a subnet created, but only for the create_nsg = true, there has to be a nsg created.

resource "azurerm_subnet" "subnet" {
  for_each             = var.subnet
  name                 = "sn-${each.key}"
  resource_group_name  = var.resourcegroup
  virtual_network_name = azurerm_virtual_network.vnet.name
  address_prefixes     = [each.value.cidrsubnet]
}

resource "azurerm_network_security_group" "nsg-subnet" {
  for_each            = var.subnet[*].create_nsg ? 1 : 0
  name                = "nsg-${each.key}"
  location            = var.location
  resource_group_name = var.resourcegroup
}

I can’t get the for_each for the nsg to work only for the create_nsg = true.

Hi @rickvanc,

The best way to think about this problem is that you need to construct a new map that contains only the subset of elements you want to declare instances for, based on this condition. For that, you can write a for expression with an if clause:

{
  for k, v in var.subnet : k => v
  if v.create_nsg
}

You can either place that expression directly in the for_each or, if you will need that smaller map in more than one resource block, assign it to a local value and then use the local value in each location which will use only this subset.