Coder Perfect

Conditional Deployment of VM Properties with Azure Bicep

Problem

Depending on the precondition, one or two NICs are used.

Anyone know if conditional statements inside a property definition can be used to deploy a VM NIC? An if function appears to be prohibited within a resource definition, and a ternary fails owing to an invalid ID.

Using resource = if (bool), I’m only attempting to avoid having two duplicate VM resource definitions.

networkProfile: {
  networkInterfaces: [
    {
      id: nic_wan.id
      properties: {
        primary: true
      }
    }

    {
      id: bool ? nic_lan.id : '' #Trying to deploy this as a conditional if bool = true.
      properties: {
        primary: false
      }
    }

  ]
}

The above code fails because a valid ID is required as soon as a NIC is defined.

‘properties.networkProfile.networkInterfaces[1]. ‘id’ is not a valid value. Fully qualified resource IDs that begin with ‘/subscriptions/subscriptionId’ or ‘/providers/resourceProviderNamespace/’ should be expected. (Code:LinkedInvalidPropertyId)

Asked by Mark Bez

Solution #1

To deal with this, you can create some variables:

// Define the default nic
var defaultNic = [
  {
    id: nic_wan.id
    properties: {
      primary: true
    }
  }
]

// Add second nic if required
var nics = concat(defaultNic, bool ? [
  {
    id: nic_lan.id
    properties: {
      primary: false
    }
  }
] : [])

// Deploy the VM
resource vm 'Microsoft.Compute/virtualMachines@2020-12-01' = {
  ...
  properties: {
    ...
    networkProfile: {
      networkInterfaces: nics
    }
  }
}

Answered by Thomas

Post is based on https://stackoverflow.com/questions/68931020/azure-bicep-conditional-deployment-of-vm-properties