jsonazureazure-powershellazure-rm-templatevnet

Addition of subnets to existing Vnet through ARM templates


The following is my input parameter file(parameter.json)

    {
    "VNetSettings":{
    "value":{
        "name":"VNet2",
        "addressPrefixes":"10.0.0.0/16",
        "subnets":[
            {
                "name": "sub1",
                "addressPrefix": "10.0.1.0/24"
            },
            {
                "name":"sub2",
                "addressPrefix":"10.0.2.0/24"
            }
        ]
    }
  }
}

The following is my arm template that should deploy the subnets.(deploy.json)

   {
"contentversion":"1.0.0.0",
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"parameters":{
        "VNetSettings":{"type":"object"},
"noofsubnets":
        {
            "type":"int"
        },
"newOrExisting":
    {
        "type":"string",
        "allowedvalues":
            [
                "new",
                "existing"
            ]
    }
    },
"resources":
[{
  "condition":"[equals(parameters('newOrExisting'),'new')]",
  "type": "Microsoft.Network/virtualNetworks",
  "mode":"Incremental",
  "apiVersion": "2015-06-15",
  "name":"[parameters('VNetSettings').name]",
  "location":"[resourceGroup().location]",
  "properties":
  {
    "addressSpace":{
        "addressPrefixes":["[parameters('VNetSettings').addressPrefixes]"]
  },
    "copy":
       [{
         "name":"subnets",
         "count":"[parameters('noofsubnets')]",
         "input": 
             {
              "name": "[parameters('VNetSettings').subnets[copyIndex('subnets')].name]",
              "properties":
                 {
                   "addressPrefix": "[parameters('VNetSettings').subnets[copyIndex('subnets')].addressPrefix]"
                 }
             }
        }]

       }
  }]
}

What the template should be doing is add these two subnets(sub1 & sub2) to the Vnet in addition to the existing subnets if there is already one.But what it is doing is replacing the existing subnets with these two subnets present in the input file. Mode: Incremental should be doing this but I'm not sure whether I'm placing it in the right place. I'm deploying this template using the following powershell commmand:

    New-AzureRmResourceGroupDeployment -Name testing -ResourceGroupName rgname -TemplateFile C:\Test\deploy.json -TemplateParameterFile C:\Test\parameterfile.json

Solution

  • This is expected behavior. you should read on 'Idempotence'. what you need to do is create a subnet resource, that way you will work around it.

    {
        "apiVersion": "2016-03-30",
        "name": "vnetName\subnetName",
        "location": "[resourceGroup().location]]",
        "type": "Microsoft.Network/virtualNetworks/subnets",
        "properties": {
            "addressPrefix": "xx.x.x.xx"
        }
    }
    

    vnetName has to be the vnet you want to create resource in.