azureazure-virtual-networkazure-bicep

Bicep: How can I optionally set a property?


I am creating a subnet, and need to optionally add a routetable.

I optionally create a route table, based on an input parameter named hasRouteTable.

Here is the call to setup the route table, which works:

module routetable 'route_table.bicep' = if (hasRouteTable){
  name: '${deployment().name}-rt'
  scope: resourceGroup()
  params: {
    routeTableName: 'myRouteTable'
    routeName: 'myRouteName'
  }
}

This is how I associate the routeTable:

resource subnet 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
  name: name
  parent: vnet
  properties: {
    addressPrefix: range
    routeTable: {
       id:hasRouteTable?routetable.outputs.routeTableID:null
    }
  }
}

If hasRouteTable is true, the route table will be created and the subnet routeTable property will be set to the id of the route table. If hasRouteTable false, the id is set to null.

Setting the route table will work, but setting it to null gives this error:

Value for the id property is invalid. Expecting a string. Actual value is Null. Path properties.routeTable. (Code: InvalidJsonPropertyType)

How can I accomplish this?


Solution

  • You should set the entire routeTable attribute to null, not just the nested id attribute.

    resource subnet 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
      name: name
      parent: vnet
      properties: {
        addressPrefix: range
        routeTable: hasRouteTable ? {
          id: routetable.outputs.routeTableID
        } : null
      }
    }
    

    When the hasRouteTable variable evaluates to false, the resulting template will be:

    resource subnet 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
      name: name
      parent: vnet
      properties: {
        addressPrefix: range
        routeTable: null
      }
    }