Azure Resource Manager Template: Conditional Deployment - azure

I'm working on an ARM template and need to perform conditional deployment. For instance, I've got two network security groups defined in a variable 'subnets'.
"variables": {
"subnets": [
{
"subnetname": "AzureBastionSubnet",
"nsgname": "nsg_bastion1"
},
{
"subnetname": "client-subnet",
"nsgname": "nsg_client1"
}
]
}
The network security group 'nsg_bastion1' needs special treatment with predefined rules since it is a network security group for an Azure Bastion subnet.
'nsg_client1' will get some custom rules assigned, which don't matter at this point.
In order to differentiate between non-Bastion and Bastion-network security groups, I've created two conditional resource blocks:
"resources": [
// NSG (non-Bastion)
{
"condition": "[not(equals(variables('subnets')[copyIndex()].name, 'AzureBastionSubnet'))]",
"name": "[variables('subnets')[copyIndex()].nsg]",
"type": "Microsoft.Network/networkSecurityGroups",
"apiVersion": "2019-11-01",
"location": "[parameters('location')]",
"properties": {},
"copy": {
"name": "nsg-c",
"count": "[length(variables('subnets'))]"
}
},
// NSG (Bastion)
{
"condition": "[equals(variables('subnets')[copyIndex()].name, 'AzureBastionSubnet')]",
"name": "[variables('subnets')[copyIndex()].nsg]",
"type": "Microsoft.Network/networkSecurityGroups",
"apiVersion": "2019-11-01",
"location": "[parameters('location')]",
"properties": {},
"resources": [
// Bastion Security Rules .....
],
"copy": {
"name": "nsg-bastion-c",
"count": "[length(variables('subnets'))]"
}
},]
The condition property checks whether the subnet is called 'AzureBastionSubnet' or not. I've verified that this works for both resource blocks alone, but it doesn't when they're included both in the code. It always throws the following error message:
Code=InvalidTemplate; Message=Deployment template validation failed:
'The resource 'Microsoft.Network/networkSecurityGroups/AzureBastionSubnet' at line '' and column '' is defined multiple times in a template.
I'd appreciate any help, thanks in advance!

Ok, I thought we had fixed this but not yet...
Even though your conditions are mutually exclusive, you can't have 2 resources with the same resourceId in the same template.
I'm guessing the difference between the two is in the securityRules? If so, simplest option may be to define 2 separate vars and then use an if() statement to swap between them based on your condition.
Failing that if you want to expand on the template can see if there is a better option...

Related

Azure ARM template depend on resources in copy loop

I am creating ARM template which takes in hash table of subnets and creates those. However, it looks that I need to wait for the first subnet to be ready before creating the second etc. But I do not know how I could depend on the previous subnet in copy loop. My template resource looks like this currently:
{
"apiVersion": "2018-06-01",
"type": "Microsoft.Network/virtualNetworks/subnets",
"name": "[concat(parameters('vnetName') , '/' , parameters('subnets').settings[copyIndex()].name)]",
"location": "[variables('location')]",
"copy": {
"name": "subnetLoop",
"count": "[variables('subnetcount')]"
},
"dependsOn": ["[parameters('vnetName')]",
"[resourceId(variables('rgname'), 'Microsoft.Network/virtualNetworks/subnets', parameters('vNetName'), parameters('subnets').settings[copyIndex()].name)]"
],
"properties": {
"addressPrefix": "[parameters('subnets').settings[copyIndex()].addressPrefix]",
}
Which does not work because the first subnet cannot reference itself.
you can use "mode": "serial" to workaround that.
"copy": {
"name": "subnetLoop",
"count": "[variables('subnetcount')]",
"mode": "serial"
},
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-multiple#resource-iteration
but you really need to look at properties loop, check this link:
https://learn.microsoft.com/en-us/azure/architecture/building-blocks/extending-templates/objects-as-parameters#using-a-property-object-in-a-copy-loop

Deploy nested resources separately

Due to separation of duty I need to split an existing ARM template into two single templates - one for the resource and one for the logging
the original templates looks like this:
"resources": [
{ // https://learn.microsoft.com/en-us/azure/templates/microsoft.datafactory/factories
"type": "Microsoft.DataFactory/factories",
"name": "[variables('dataFactoryName')]",
"apiVersion": "[variables('apiVersion')]",
"location": "[resourceGroup().location]",
"tags": {},
"identity": {
"type": "SystemAssigned"
},
"properties": {},
"resources": [
{
"type": "providers/diagnosticSettings",
"name": "[concat('Microsoft.Insights/', variables('logSettingName'))]",
"dependsOn": [
"[resourceId('Microsoft.DataFactory/factories', variables('dataFactoryName'))]"
],
"apiVersion": "2017-05-01-preview",
"location": "[resourceGroup().location]",
"tags": {},
"properties": {
"name": "[variables('logSettingName')]",
"workspaceId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', parameters('logAnalyticsObject').resourceGroup, '//providers/Microsoft.OperationalInsights/workspaces/', parameters('logAnalyticsObject').name)]",
"logs": "[parameters('logAnalyticsObject').adfv2.logs]",
"metrics": "[parameters('logAnalyticsObject').adfv2.metrics]"
}
}
]
}
The first part is quite easy, I just remove the sub-resource but how to get the second part (resource with "type": "providers/diagnosticSettings") correctly so it can be deployed from a different template?
Is this possible at all or are these strongly tied together?
I already tried different things like
"type": "Microsoft.DataFactory/factories/providers/diagnosticSettings",
"name": "[concat('Microsoft.Insights/', variables('name'))]",
but ended up with error messages like this:
Unable to process template language expressions for resource '/subscriptions/fb1e20c4-0878-4949-ac10-f92a9ac35db4/resourceGroups/swe-sdp-dv0
-rgp-adp/providers/Microsoft.Resources/deployments/DataFactory_LogAnalytics_Resource' at line '67' and column '5'. 'Unable to evaluate template language
function 'resourceId': function requires exactly one multi-segmented argument which must be resource type including resource provider namespace. Current
function arguments 'fb1e20c4-0878-4949-ac10-f92a9ac35db4,swe-sdp-dv0-rgp-anl,Microsoft.Insights,swe-sdp-dv0-oms-001'. Please see
https://aka.ms/arm-template-expressions/#resourceid for usage details.
I think to make it work I would need the right combination of "type", "name" and probably also "dependsOn"
ok, according to this, you would need to do this:
"type": "Microsoft.DataFactory/factories/providers/diagnosticSettings",
"name": "[concat(variables('dataFactoryName'), '/Microsoft.Insights/', variables('name'))]",
you dont need dependsOn, because resources are under different templates.

arm template virtualNetworkName creation appendix issue

I am trying to get a arm template running and have hit an issue with the virtualnetwork creation.
azuredeploy.json
"virtualNetworkName": {
"type": "string",
"metadata": {
"description": "Name of virtual network to be created"
},
"defaultValue": "autohav2VNET"
},
vnet-net.json
"resources": [
{
"name": "[parameters('virtualNetworkName')]",
"type": "Microsoft.Network/virtualNetworks",
"location": "[parameters('location')]",
"apiVersion": "2015-06-15",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[parameters('virtualNetworkAddressRange')]"
]
},
"subnets": "[parameters('subnets')]"
}
}
]
The issue I am getting is that the vnet gets created with an appendix such as this: autohav2VNETl5g
So when this gets used to create a loadblancer, the names doe not match the defined parameter and the creation fails.
..../virtualNetworks/AUTOHAV2VNET referenced by resource .... /Microsoft.Network/loadBalancers/sqlLoadBalancer was not found.
Any suggestions?
with the data given it impossible to be sure why this is happening. you are probably passing in a value to the parameter virtualNetworkName. because if you wouldn't, than the vnet name would be: autohav2VNET.
ARM templates do not append anything anywhere just because they are arm templates. they only do what you designed them to do.
to help with debugging: how you are invoking the template and full template + full parameters file.

ARM template, Incorrect Segment Lengths

I'm trying to build an ARM template and keep getting the error:
'The template resource 'udr-sub-w05-w05-w05-agw-10.10.10.32/27' for type
'Microsoft.Network/routeTables' at line '141' and column '5' has incorrect segment lengths. A nested resource type must have identical number of segments as its resource name. A root resource type must
have segment length one greater than its resource name.
The nested template for create route tables code is below:
{
"name": "[variables('routeTable1')]",
"type": "Microsoft.Network/routeTables",
"apiVersion": "[variables('routeTableApiVersion')]",
"location": "[resourceGroup().location]",
"properties": {
"routes": [
],
"disableBgpRoutePropagation": false
}
},
{
"name": "[variables('routeTable2')]",
"type": "Microsoft.Network/routeTables",
"apiVersion": "[variables('routeTableApiVersion')]",
"location": "[resourceGroup().location]",
"properties": {
"routes": [
],
"disableBgpRoutePropagation": false
}
},
Any idea where this is going wrong? I've spent some time googling and my understanding is the "TYPE" should have one less segment than the "NAME", which I believe it has
"name": "[variables('routeTable1')]",
"type": "Microsoft.Network/routeTables",
Route table one variables
"routeTable1": "[tolower(concat('udr-', variables('subnetName1')))]",
"routeTable2": "[tolower(concat('udr-', variables('subnetName2')))]",
Thanks
Your route table name contains /, hence it thinks you are trying to create a sub resource and asks you to provide its type (you only provide parent resource type). remove the /27 thing or replace it with -27 or something like that.

How to define specific Resource Group in Azure Resource Manager nested template

Does anyone know how to place Resources in an ARM template into specific, and different Resource Groups? This might be the storage in one RG and the network in another, both created in the same, or different, templates (nested, for example).
Full details are below.
Reading through the best practice guide ARM template best practice and the whitepaper World Class ARM Templates Considerations and Proven Practices there's a recommendation that different elements of a deployment should be situated in separate Resource Groups. For example, in an IaaS solution, your DCs might sit in an Admin RG, your back-end servers in another, and your client desktops in a third.
I'm currently trying to deploy such a solution via nested templates, and I've stumbled upon an issue whereby all items being created are automatically placed inside the Resource Group selected when kicking the process off (i.e. the parent template). I've looked through the various documentation online but can't obviously find a way to force resources being created in a template into a specific Resource Group. Has anyone done this?
For anyone else that finds this in google (like I did):
It is now possible to deploy resources to multiple resource groups in one ARM template. Microsoft has details available here: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-cross-resource-group-deployment for the details.
To do this you include a nested deployment template within the main one, and set the nested deployment to another resource group. here is an example from the MS Site:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storagePrefix": {
"type": "string",
"maxLength": 11
},
"secondResourceGroup": {
"type": "string"
},
"secondSubscriptionID": {
"type": "string",
"defaultValue": ""
},
"secondStorageLocation": {
"type": "string",
"defaultValue": "[resourceGroup().location]"
}
},
"variables": {
"firstStorageName": "[concat(parameters('storagePrefix'), uniqueString(resourceGroup().id))]",
"secondStorageName": "[concat(parameters('storagePrefix'), uniqueString(parameters('secondSubscriptionID'), parameters('secondResourceGroup')))]"
},
"resources": [
{
"apiVersion": "2017-05-10",
"name": "nestedTemplate",
"type": "Microsoft.Resources/deployments",
"resourceGroup": "[parameters('secondResourceGroup')]",
"subscriptionId": "[parameters('secondSubscriptionID')]",
"properties": {
"mode": "Incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('secondStorageName')]",
"apiVersion": "2017-06-01",
"location": "[parameters('secondStorageLocation')]",
"sku":{
"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {
}
}
]
},
"parameters": {}
}
},
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('firstStorageName')]",
"apiVersion": "2017-06-01",
"location": "[resourceGroup().location]",
"sku":{
"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {
}
}
]
}
It is not possible to deploy resources into multiple resource groups from a template. Simply by virtue of the fact that the Azure Resource Manager REST API Reference only has a single place to specify the resource group name.
The concept of ARM templates is that you create a resource group and deploy a template into it, and thus provide a single administrative unit from which to manage those resources. This improves over the Azure Service Management model where you had to manage each resource individually.
Nested resource groups would be quite a nice feature to fulfill your need, but I've never heard of such a thing being planned for Azure.

Resources