Search code examples
azureazure-virtual-networkazure-bicep

idempotency of resource creation in microsoft azure creating a virtual network


I am trying to create som infrastructure on azure.

I have a bicep module that looks like this:

param location string
param virtualNetworkName string

resource virtualNetwork 'Microsoft.Network/virtualNetworks@2019-11-01' = {
  name: virtualNetworkName
  location: location
  properties: {
    addressSpace: {
      addressPrefixes: [
        '10.0.0.0/16'
      ]
    }
  }
}

and I call it from my main bicep file

module createCommonVirtualNetwok 'modules/createVirtualNetwork.bicep' = {
  name: 'createCommonVirtualNetwokModule'
  scope: resourceGroup(commonResourceGroupName)
  dependsOn: [
    createResourceGroupModule_common
  ]
  params:{
    virtualNetworkName: commonVNetName
    location: location
  }
}

it works fine and creates the vnet. I also have another module that adds subnets to this vnet which also works. and a containerapp is later set up to use said subnet.

so far so good.

but when I run the script again at this point it fails on the Virtual network creation module. the deployment operation details say:

Subnet my-subnet is in use by /subscriptions/<mysubid>/resourceGroups/MC_<some-resourcegroup>/providers/Microsoft.Network/networkInterfaces/|providers|Microsoft.Compute|virtualMachineScaleSets|aks-agentpool-<someid>-vmss|virtualMachines|3|networkInterfaces|aks-agentpool-<someid>-vmss/ipConfigurations/ipconfig1 and cannot be deleted. In order to delete the subnet, delete all the resources within the subnet. See aka.ms/deletesubnet."

well, it makes sense in a way - It does not want to delete the subnet until its not used... but I don't recall asking it to create the v-net. or maybe the fact that I do not specify any subnets makes it think that I want existing subnets to be removed?

how can I just ensure that this resource exists and create it if it does not exists without having it try to kill its child resources if they already exist?


Solution

  • this is expected and is a long debated behaviour of vnets\subnets and a couple of other parent\child resources.

    https://github.com/Azure/azure-quickstart-templates/issues/2786

    there is nothing you can do about it really, except for create vnet and subnets in the same arm template\bicep file or use some other tool (pulumi, powershell, terraform, etc) which do individual api calls per resource