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

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

Multiple conditions for Bicep resource deployments

After working with Bicep templates we have discovered a useful mechanism, multiple conditions. Multiple conditions provide ways to be more specific in the way we perform conditional deployments and enable us to have more control on the conditions we match on.

Read More »

Arinco trades as Arinco (VIC) Pty Ltd
and Arinco (NSW) Pty Ltd

All Rights Reserved


Level 9, 360 Collins Street, 
Melbourne VIC 3000

Level 2, 24 Campbell St,
Sydney NSW 2000

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.