Search code examples
azureazure-bicepbicep

Azure Bicep - optional property based on a condition


In Bicep, how can I define a property on a resource only if it matches a condition? For instance if I want to create an Azure Service Bus Standard Tier in my non-prod environment, then in it certain properties like "capacity" and "zoneRedundant" are not allowed properties, but they are allowed if I want to create a Premium Tier in my prod env.

resource serviceBusNamespace 'Microsoft.ServiceBus/namespaces@2022-10-01-preview' = {
  name: serviceBusNamespaceName
  location: location
  sku: {
    name: (environmentName == 'prod') ? 'Premium' : 'Standard'
    //capacity: 1               
  }
  identity: {                 
    type: 'SystemAssigned'  
  }
  properties: {
    //zoneRedundant: (environmentName == 'prod') ? true : false
    disableLocalAuth: true  
  }
}

Solution

  • You should set the property to null to omit the property:

    resource serviceBusNamespace 'Microsoft.ServiceBus/namespaces@2022-10-01-preview' = {
      name: serviceBusNamespaceName
      location: location
      sku: {
        name: (environmentName == 'prod') ? 'Premium' : 'Standard'
        capacity: (environmentName == 'prod') ? 1 : null
      }       
    }
    

    A consideration could be the configuration set pattern. It allows you to more easily omit properties that you do not need and simplifies your template because you do not need all the ternary operators.

    @description('Required. The environment type.')
    @allowed([
      'prd' 
      'dev'
    ])
    param environmentType string
    
    // The configuration map, contains environment-specific values.
    var configurationMap = {
      prd: {
        serviceBusNamespace: {
          zoneRedundant: true
          sku: {
            name: 'Premium'
            capacity: 1
          }
        }
      }
      dev: {
        serviceBusNamespace: {
          zoneRedundant: false
          sku: {
            name: 'Standard'
          }
        }
      }
    }
    
    // The resource declaration, uses the values from the configuration map,
    // based on the environment type specified in the environmentType parameter.
    resource serviceBusNamespace 'Microsoft.ServiceBus/namespaces@2022-10-01-preview' = {
      name: serviceBusNamespaceName
      location: location
      sku: configurationMap[environmentType].serviceBusNamespace.sku
      properties: {
        zoneRedundant: configurationMap[environmentType].serviceBusNamespace.zoneRedunant
      }
    }