Blogs

Azure Pro Tip Series: ARM templates and IF statements on resources with id segment

This is going to be the first of many blogs where we share some pro tips we come across when deploying to Azure.

Today we will be diving into IF statements with ARM templates and how to use them on resources that have an id segment.

Typical example is when deploying a virtual network using an ARM template. For each subnet you need to provide a network security group and/or route table if you want to associate one to the subnet, as per below.

{
    "name": "[parameters('subnetName')]",
    "properties": {
        "addressPrefix": "[parameters('subnetPrefix')]",
        "routeTable": {
            "id": "[resourceId('Microsoft.Network/routeTables', parameters('routeTableName'))]"
        },
        "networkSecurityGroup": {
            "id": "[resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroupName'))]"
        }
    }
}

Have you ever tried to put a IF statement in the id segment as per below? You may have found it only works if you supply a value, if you leave it empty or null the deployment will fail.

"networkSecurityGroup": {
    "id": "[if(not(empty(parameters('networkSecurityGroupName'))), resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroupName')), json('null'))]"
}

PRO TIP!
Move the id segment into your IF statement and it will solve the issue.

As we know the id segment cannot be null, even though the network security group can be null, it still requires a JSON value. So in this case we are creating a string representation of the id as JSON and then converting it to a JSON object using the JSON function .

Example below.

"networkSecurityGroup": "[if(not(empty(parameters('networkSecurityGroupName'))), json(concat('{\"id\": \"', resourceId('Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroupName')), '\"}')), json('null'))]"
[mailpoet_form id="1"]

Other Recent Blogs

Level 9, 360 Collins Street, 
Melbourne VIC 3000

Level 2, 24 Campbell St,
Sydney NSW 2000

200 Adelaide St,
Brisbane QLD 4000

191 St Georges Terrace
Perth WA 6000

Level 10, 41 Shortland Street
Auckland

Part of

Arinco trades as Arinco (VIC) Pty Ltd and Arinco (NSW) Pty Ltd. © 2023 All Rights Reserved Arinco™ | Privacy Policy
Arinco acknowledges the Traditional Owners of the land on which our offices are situated, and pay our respects to their Elders past, present and emerging.

Get started on the right path to cloud success today. Our Crew are standing by to answer your questions and get you up and running.