Search code examples
azureazure-resource-managerazure-managed-identityazure-bicep

Assign Multiple Azure Roles to a resource using Bicep


I want to create a pipeline, where I use Bicep template file to assign more than one built-in Role to Managed Identity. I thought about creating Role Definition by Bicep first, but it's input demands putting specific permissions, which is a bit messy, bacause I'd need to put more than 70 permissions to that template, so I thought about deploying Role Assignment only instead. From what I see in MS documentation here it is possible, but only by specifying one specific Role Definition. Is it possible to define more than one Role Defintion in bicep template to assign them to a resource? I want to avoid creating role definition bicep template with a huge list of specific permissions.


Solution

  • You can always pass an array of role definition and loop through:

    param storageAccountName string
    param principalId string
    param principalType string = 'ServicePrincipal'
    param roleDefinitionIds array
    
    // Get a reference to the existing resource
    resource storageAccount 'Microsoft.Storage/storageAccounts@2021-04-01' existing = {
      name: storageAccountName
    }
    
    // Create the role assignments
    resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = [for roleDefinitionId in roleDefinitionIds: {
      scope: storageAccount
      name: guid(storageAccount.id, principalId, roleDefinitionId)
      properties: {
        roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionId)
        principalId: principalId
        principalType: principalType
      }
    }]