How to use if else in ARM template azure

Viewed 514

I have created sample function here in c# which set the location value based on the parameter. I want to write below expression by using arm template style format.

public static Main(string name)
{
    string location = string.Empty;
    if(name == "uksouth")
    {
        location = "UKS";
    }else if(name == "ukwest")
    {
        location = "UKE";
    }else if(name == "IndiaWest")
    {
        location = "INDW";
    }
    else {
        location = "INDS";
    }

}

I have written this for one match condition, but i want to return value based on the user resource group.

"value": "[if(equals(resourceGroup().location,'uksouth'), 'UKS', 'EUS')]"
2 Answers

Unfortunately, ARM templates don't provide the equivalent of a "switch" mechanism, which is what might make this easier. However, you can nest multiple if statements. The syntax is a bit clunky, but this should be the equivalent of the code you've written:

"value": "[if(equals(resourceGroup().location,'uksouth'), 'UKS', [if(equals(resourceGroup().location,'ukwest'), 'UKE', [if(equals(resourceGroup().location,'IndiaWest'), 'INDW', 'INDS')])])]"

Here's the same code with a little formatting applied to make it more obvious what's happening here:

"value": "
    [if(equals(resourceGroup().location,'uksouth'), 
        'UKS', 
    [if(equals(resourceGroup().location,'ukwest'), 
        'UKE', 
    [if(equals(resourceGroup().location,'IndiaWest'), 
        'INDW', 
    'INDS')])])]
"

You might also consider the approach described in this answer for a bit of a cleaner solution.

Try defining a variable that is an object used like a hashtable. Retrieve different properties from the object by key-name, accessing the properties as key-value pairs. I use something very similar to lookup values inside my ARM templates.

"variables" {
  "locationShorten": {
    "uksouth": "UKS",
    "ukwest": "UKE",
    "IndiaWest": "INDW",
    "IndiaSouth": "INDS"
  },
  "locationShort": "[variables('locationShorten')[resourceGroup().location]]"}

Microsoft defines an object's properties as key-value pairs. "Each property in an object consists of key and value. The key and value are enclosed in double quotes and separated by a colon (:)." Source: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/data-types#objects

As for the documentation on using [] to access object properties, I can no longer find it for JSON but it is there for BICEP. "You can also use the [] syntax to access a property." Source: https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/data-types#objects

Related