Dynamic Arm Templates With Inline Logic Operators

A while back I wrote an article talking about the new “Condition” option in Azure Resource Manger (ARM) templates. This was the first step into conditional logic in ARM templates and worked great where you needed to apply a condition at the resource level. Where it fell down was where you needed a condition inside a resource, this resulted in you having to duplicate objects with different settings and work around issues like duplicate naming. In our example we looked at whether or not a network card should have a public IP. The condition worked great for determining whether or not to create the Public IP (PIP) object, but when it came to deciding whether or not to assign the PIP to the network card we ended up having to create two network card objects, one with one without, and use the condition to select which one to use, a bit painful!

I’m happy to say a new update to the ARM template specification adds more options for conditional logic in your ARM templates. In particular, alongside conditions we now have IF statements which you can use inline in your code to conditionally make choices at run time, which can be really powerful. The syntax of this is pretty straightforward:

[if(condition, true value, false value)]

These if statements can be applied to parameters, variables and most importantly resource properties. This new set of language features is a great addition to the toolbox for building more dynamic and re-usable templates. It’s not perfect, if your using IFs with complex JSON objects you end up having to store this as variables and end up growing that out very quickly, especially if you want to use an IF statement to decide between two different complex objects. Additionally, if you want to do something like if, if then, else, you end up having to next multiple IFs which can get pretty complicated to read. All of these compromises however, are still better than having to duplicate whole objects like we did before and we now have a pretty powerful set of tools to be able to control what we deploy dynamically at run time, and most importantly help us make scripts that are generic enough to share around.

It should be noted that If statements don’t do away with the need for Conditions, but more likely you will use these two in combination like we have here. Where you need to determine whether an entire resource is deployed or not, use conditions, where you need to alter inline elements use an if statement.