Search code examples
azureazure-functionsazure-rm-templateazure-managed-identity

Add User Assigned Managed Identity in a Function App Template Conditionally


Is there a way to update the below template to include IDENTITY_RESOURCE_ID1 conditionally if addIdentity1 parameter is set to true?

{
    "apiVersion": "2018-11-01",
    "name": "[parameters('name')]",
    "type": "Microsoft.Web/sites",
    "kind": "functionapp",
    "location": "[parameters('location')]",
    "identity": {
        "type": "SystemAssigned,UserAssigned",
        "userAssignedIdentities": {
            "IDENTITY_RESOURCE_ID1": {},
            "IDENTITY_RESOURCE_ID2": {}
        }
    },
    "tags": null,
    // ...
}

Solution

  • You can use the union function.

    Here is a bicep sample (main.bicep):

    param location string = resourceGroup().location
    param name string
    param addIdentity1 bool
    
    resource webApp 'Microsoft.Web/sites@2018-11-01' = {
      name: name
      location: location
      identity: {
        type: 'SystemAssigned, UserAssigned'
        userAssignedIdentities: union(
          {
            'IDENTITY_RESOURCE_ID2': {}
          },
          addIdentity1
            ? {
                'IDENTITY_RESOURCE_ID1': {}
              }
            : {}
        )
      }
    }
    

    Running the Az Cli command az bicep build --file .\main.bicep, will give you this ARM template:

    {
      "type": "Microsoft.Web/sites",
      "apiVersion": "2018-11-01",
      "name": "[parameters('name')]",
      "location": "[parameters('location')]",
      "identity": {
        "type": "SystemAssigned, UserAssigned",
        "userAssignedIdentities": "[union(createObject('IDENTITY_RESOURCE_ID2', createObject()), if(parameters('addIdentity1'), createObject('IDENTITY_RESOURCE_ID1', createObject()), createObject()))]"
      }
    }