Creating resource groups, using ARM templates

One of the latest additions to the capabilities of ARM templates is resource group creation. In the past, it was not possible to create resource groups using ARM templates. Generally, templates are deployed to a resource group. As of the writing of this chapter, the PowerShell modules are not yet updated to deploy to a subscription instead of a resource group. However, the capability to conduct a deployment at the subscription level is added to Azure CLI. In this section, we will deploy a template that will create multiple resource groups within a subscription. The entire code for this ARM template is available with the chapter-accompanied code file: chapter-4 - listing10.txt:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"Locations": {
"type": "array",
"defaultValue": [ "east us", "west us" ],
"metadata": {
"description": "Deployment locations"
}
}
},
"variables": {
},
"resources": [
{
"type": "Microsoft.Resources/resourceGroups",
"location": "[parameters('Locations')[copyIndex()]]",
"name": "[concat('location',copyIndex())]",
"apiVersion": "2018-05-01",
"copy": {
"name": "allResourceGroups",
"count": "[length(parameters('Locations'))]"
},
"properties": {}
}
]
}

To deploy this template, Azure CLI should be used, as shown next:

az login -u <<your username>> -p <<your password>>

az account set --subscription <<your subscription id or subscription name>>

az deployment create --location WestUS --template-file "<<location of above template>>" --verbose

Deploying this template will create two resource groups—one in the eastern US and the other in the western US. You should check the way expressions and functions are used to get the count for the resource group provisioning, and use the copyindex function to read them, by indexing the parameter of the array type.