Search code examples
azureazure-bicep

How can I create an array of subnets on an existing vnet using Bicep?


In my bicep file I obtain a reference to the existing vnet like this:

resource existingVNET 'Microsoft.Network/virtualNetworks@2021-02-01' existing = {
  name: 'the-existing-vnet'
}

I have tried to include multiple (four to be exact) resource statements for each of the subnets like this:

resource subnetPbdResource 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
  parent: existingVNET
  name: 'first-snet'
  ...
}
resource subnetPbdResource 'Microsoft.Network/virtualNetworks/subnets@2020-11-01' = {
  parent: existingVNET
  name: 'second-snet'
  ...
}

...however, when I run this (using az deployment group create ...) I get an error: with code AnotherOperationInProgress. One random (it seems) subnet has been created under the vnet.

I've also tried to define an array of subnets like this:

var subnets = [
  {
    name: 'api'
    subnetPrefix: '10.144.0.0/24'
  }
  {
    name: 'worker'
    subnetPrefix: '10.144.1.0/24'
  }
]

...but I cannot find a way to assign the existing vnet with the subnets array. .properties.subnets is not accessible for the existing vnet resource it seems.

Any tip appreciated!


Solution

  • I also got a great answer on Bicep github discussion

    Basically it boils down to building an array of subnets, use @batchSize(1) to ensure serial creation of subnets (I guess this achieves the same as using dependsOn in answer from @Manuel Batsching) and pass the subnet array as parameter to Resource "create subnet statement". Obvious advantage: no duplicate code to create subnet