azureazure-resource-managerazure-virtual-networkazure-bicep

Bicep - optionally add a network security group


I am creating a subnet with the following bicep:

resource nsg 'Microsoft.Network/networkSecurityGroups@2023-05-01' existing = {
  name: networkSecurityGroupName
}
resource subnet 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
  name: name
  parent: vnet
  properties: {
    addressPrefix: range
    networkSecurityGroup: {
      id: nsg.id
    }
    delegations: [
      {
        name: 'delegation'
        properties: {
          serviceName: 'Microsoft.Web/serverfarms'
        }
        type: 'Microsoft.Network/virtualNetworks/subnets/delegations'
      }
    ]
    privateEndpointNetworkPolicies: 'Disabled'
    privateLinkServiceNetworkPolicies: 'Enabled'
  }
}

As you see, this bicep is setting the network security group (NSG).

However, some of the subnets will not have a NSG, so none is passed in.

How can I optionally include the NSG?

I've tried this:

   networkSecurityGroup: {
      id: ((networkSecurityGroupName != '') ? nsg.id : null)
    }

It's not valid because the id cannot be null. Somehow I need to omit the entire networkSecurityGroup property.

I moved the NSG to a module like this:

module subnetNSG './subnet_nsg.bicep' = if (networkSecurityGroupName != '') {
  name: '${deployment().name}-subnet.Deploy'
  params: {
    name: name
    vnetName: vnetName
    networkSecurityGroupName: networkSecurityGroupName
  }
}

It will optionally call the module. The module has this resource:

resource subnetNSG 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
  name: name
  parent: vnet
  properties: {
    networkSecurityGroup: {
      id: nsg.id
    }
  }
}

This fails with:

Address prefix string for resource cannot be null or empty.


Solution

  • You were close with:

    networkSecurityGroup: {
      id: ((networkSecurityGroupName != '') ? nsg.id : null)
    }
    

    You need to set the condition on the networkSecurityGroup object property:

    networkSecurityGroup: !empty(networkSecurityGroupName) ? {
      id: nsg.id
    } : null