Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Bicep - Conditionally adding elements to an array

I am trying to create a bicep template to deploy a VM with either 1 or 2 NICs depending on a conditional.

Anyone know if there is a way to deploy a VM NIC using conditional statements inside a property definition? Seems an if function is not permitted inside a resource definition and a ternary errors out due to invalid ID.

Just trying to avoid having 2 dupicate VM resource definitions using resource = if (bool) {}

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 errors out because as soon as you define a NIC, it needs a valid ID.

'properties.networkProfile.networkInterfaces[1].id' is invalid. Expect fully qualified resource Id that start with '/subscriptions/{subscriptionId}' or '/providers/{resourceProviderNamespace}/'. (Code:LinkedInvalidPropertyId)

like image 971
Mark Bez Avatar asked Jul 11 '26 23:07

Mark Bez


2 Answers

You can create some variables to handle that:

// 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
    }
  }
}
like image 67
Thomas Avatar answered Jul 14 '26 12:07

Thomas


Building on Thomas answer, you can use the spread operator:

resource vm 'Microsoft.Compute/virtualMachines@2024-11-01' = {
  // ...
  properties: {
    // ...
    networkProfile: {
      networkInterfaces: [
        {
          id: nic_wan.id
          properties: {
            primary: true
          }
        }
        ...(bool ? [
          {
            id: nic_lan.id
            properties: {
              primary: false
            }
          }
        ] : [])
      ]
    }
  }
}
like image 30
EriF89 Avatar answered Jul 14 '26 13:07

EriF89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!