Coder Perfect

How can I use Bicep to construct an array of subnets on an existing vnet?

Problem

I get a reference to the existing vnet like this in my bicep file:

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

For each of the subnets, I tried to include multiple (four to be exact) resource statements 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'
  ...
}

…but, I receive an error: with code AnotherOperationInProgress when I run this (using az deployment group create…). Under the vnet, one seemingly random subnet has been constructed.

I’ve also attempted to define an array of subnets in the following manner:

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

.properties, but I can’t seem to find a way to attach the existing vnet to the subnets array. It appears that subnets are not accessible for the existing vnet resource.

Any tip appreciated!

Asked by Caad9Rider

Solution #1

When ARM tries to deploy many subnet resources at the same time, it appears to become twisted up.

You can use dependsOn to ensure that the subnets are generated in order:

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
  ]
}

Answered by Manuel Batsching

Solution #2

On the Bicep github conversation, I also received a fantastic response.

Basically, generate an array of subnets, use @batchSize(1) to assure serial subnet generation (I assume this achieves the same result as using dependsOn in @Manuel Batsching’s response), then send the subnet array as an argument to Resource’s “create subnet statement.” The obvious benefit is that there is no need to duplicate code in order to construct a subnet.

Answered by Caad9Rider

Post is based on https://stackoverflow.com/questions/68225506/how-can-i-create-an-array-of-subnets-on-an-existing-vnet-using-bicep