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

Viewed 1945

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 ...)a 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!

2 Answers

It seems that ARM gets tangled up when it tries to deploy more than one subnet resource at the same time.

You can use dependsOn to make sure the subnets get created one after another:

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

resource subnetPbdResource 'Microsoft.Network/virtualNetworks/subnets@2021-02-01' = {
  name: 'first-snet'
  parent: existingVNET
  properties: {
    addressPrefix: '10.0.1.0/24'
  }
}

resource subnetPbdResource2 'Microsoft.Network/virtualNetworks/subnets@2021-02-01' = {
  name: 'second-snet'
  parent: existingVNET
  properties: {
    addressPrefix: '10.0.2.0/24'
  }
  dependsOn: [
    subnetPbdResource
  ]
}

resource subnetPbdResource3 'Microsoft.Network/virtualNetworks/subnets@2021-02-01' = {
  name: 'third-snet'
  parent: existingVNET
  properties: {
    addressPrefix: '10.0.3.0/24'
  }
  dependsOn: [
    subnetPbdResource2
  ]
}

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

Related