Wednesday, 11 January 2017

Deploying Azure Virtual Networks with multiple CIDR addresses using ARM templates

I recently had to craft an ARM template in Azure for a Virtual Network that had an address space that wasn't sized as a "to the power of two".

i.e. this would be simple if you're creating a Vnet for an address space of say 256 addresses, such as
10.1.0.0 - 10.1.0.255 = 10.1.0.0/24
You can use a parameter of type "string" in the template, so assuming you arrange your parameters and template into 2 files, the parameters would include:
"vnetAddressPrefix": {
    "value": "10.1.0.0/24",
}
And the template itself would include the parameters and resource definitions for the Vnet as follows:
"vnetAddressPrefix": {
    "type": "string"
}
...
"resources": [ {
    "type": "Microsoft.Network/virtualNetworks",
    "name": "my256Vnet",
    "apiVersion": "2016-03-30",
    "location": "[resourceGroup().location]",
    "properties": {
        "addressSpace": {
            "addressPrefixes": [
                "[parameters('vnetAddressPrefix')]"
            ]
        },
        "subnets": [ {
            "name": "default",
            "properties": {
                "addressPrefix": "10.1.0.0/28"
            }
        }
        ]
    }
}
]

But, lets say you need a Vnet with 384 addresses, such as
10.1.0.0 - 10.1.1.127
Because you can't specify this range in a single CIDR address, you would instead need to create an address space in CIDR notation of
10.1.0.0/24
10.1.1.0/25
The simple "string" parameter used in the first example will not work here, instead you should use a parameter of type "array", modifying the parameter file to include the CIDR ranges as follows:
"vnetAddressPrefixes": {
    "value": [
            "10.1.0.0/24",
            "10.1.1.0/25"
    ]
}
And then changing your template file to include parameters and resource definitions as follows:
"vnetAddressPrefixes": {
    "type": "array"
}
...
"resources": [ {
    "apiVersion": "2016-03-30",
    "type": "Microsoft.Network/virtualNetworks",
    "name": "my384Vnet",
    "location": "[resourceGroup().location]",
    "properties": {
        "addressSpace": {
            "addressPrefixes": 
                "[parameters('vnetAddressPrefixes')]"
        },
        "subnets": [ {
            "name": "default",
            "properties": {
                "addressPrefix": "10.1.0.63/24"
            }
        }
        ]
    }
}
]

That's it! Although it's unlikely that a deploying Vnets in a greenfield environment would require this solution, it still may happen, and is more likely to happen in an environment where address space is already constrained by other Vnets and addressing conventions.

No comments:

Post a Comment