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'))]"

Read more recent blogs

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.