Skip to main content

Assign role assignments by name in ARM templates

When you want to do a role assignment to a principal in an ARM template you will use code like the one below. In this example the role definition is actual the object id of the role. If you want to assign the contributor role you will use the value 'b24988ac-6180-42a0-ab88-20f7382dd24c'. You also have to specify the id of the principal so you will have to retrieve that value yourself upfront.

{
  "type": "Microsoft.Authorization/roleAssignments",
  "apiVersion": "2020-04-01-preview",
  "name": "[guid(parameters('roleAssignmentName'))]",
  "properties": {
    "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', parameters('roleDefinitionId'))]",
    "principalId": "[parameters('principalId')]",
    "scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', parameters('rgName'))]"
  }
}

Would it not be easier to configure role assignments by the name of the principal and the role? For example via an array like the one below.

"roleAssignments": [
    {
      "name": "myuserassignedidentity",
      "principalType": "ServicePrincipal",
      "builtInRoleType": "Contributor"
    },
    {
      "name": "DEL-MyWebApplication-Contributors",
      "principalType": "Group",
      "builtInRoleType": "Contributors"
    },
    {
      "name": "my-account@my-domain.com",
      "principalType": "User",
      "builtInRoleType": "Reader"
    }
  ]
}

To make this kind of assignment possible I utilize the concept of deployment scripts again. I wrote a PowerShell script which will retrieve the id of a managed identity, Azure AD group or user principal. This script is executed by the ARM template and will run under the rights of an user assigned identity. The identity needs reader rights on the Azure subscription and should be part of the Directory Readers Azure AD group to be able to query groups and users.

[CmdletBinding()]
param (
    # The name of the principal.
    [Parameter(Mandatory = $true)]
    [string]
    $PrincipalName,

    # The type of principal.
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet("ServicePrincipal", "Group", "User")]
    [string]
    $PrincipalType
)

# Add TLS 1.2 in session
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Install modules
if (-not (Get-Module -Name Az.Resources -ListAvailable -ErrorAction SilentlyContinue | Where-Object { $_.Version -eq "3.2.1" })) {
    # Newer versions require another version than Az.Accounts version 2.2.5.
    Install-Module -Name Az.Resources -RequiredVersion 3.2.1 -Scope CurrentUser -Force
}

# Import modules
Import-Module -Name Az.Resources -RequiredVersion 3.2.1

$contextName = (Get-AzContext).Name
Write-Output "Context: $contextName"

switch ($PrincipalType) {
    "ServicePrincipal" {
        Write-Output "Retrieve ID from Service Principal '$PrincipalName'."
        $principalId = Get-AzADServicePrincipal -DisplayName $PrincipalName | Select-Object -ExpandProperty Id
    }
    "Group" {
        Write-Output "Retrieve ID from Azure AD group '$PrincipalName'."
        $principalId = Get-AzADGroup -DisplayName $PrincipalName | Select-Object -ExpandProperty Id
    }
    "User" {
        Write-Output "Retrieve ID from Azure AD user '$PrincipalName'."
        $principalId = Get-AzADUser -UserPrincipalName $PrincipalName | Select-Object -ExpandProperty Id
    }
    default {
        $principalId = $null
    }
}

# Write the principal id to the ARM output section.
$DeploymentScriptOutputs['principalId'] = $principalId

Finally the ARM template uses this PowerShell script to retrieve the id of the principal. It also has the knowlegde of the object ids of the roles which you want to support in the form of local variables named after the roles.

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "cdStorageAccount": {
            "type": "string"
        },
        "cdStorageAccountSASToken": {
            "type": "string"
        },
        "nestedTemplateSuffix": {
            "type": "string"
        },
        "resourceGroupName": {
            "type": "string"
        },
        "roleAssignments": {
            "type": "array"
        },
        "runAsIdentity": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
            "name": "[concat('-roleAssignment', '-', padLeft(copyIndex(), 3, '0'), '-', parameters('nestedTemplateSuffix'))]",
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2020-06-01",
            "copy": {
                "name": "roleAssignmentsArray",
                "count": "[length(parameters('roleAssignments'))]",
                "mode": "Parallel"
            },
            "resourceGroup": "[parameters('resourceGroupName')]",
            "properties": {
                "mode": "Incremental",
                "expressionEvaluationOptions": {
                    "scope": "inner"
                },
                "parameters": {
                    "cdStorageAccount": {
                        "value": "[parameters('cdStorageAccount')]"
                    },
                    "cdStorageAccountSASToken": {
                        "value": "[parameters('cdStorageAccountSASToken')]"
                    },
                    "nestedTemplateSuffix": {
                        "value": "[parameters('nestedTemplateSuffix')]"
                    },
                    "resourceGroupName": {
                        "value": "[parameters('resourceGroupName')]"
                    },
                    "roleAssignment": {
                        "value": "[parameters('roleAssignments')[copyIndex()]]"
                    },
                    "runAsIdentity": {
                        "value": "[parameters('runAsIdentity')]"
                    },
                    "iterator": {
                        "value": "[padLeft(copyIndex(), 3, '0')]"
                    }
                },
                "template": {
                    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    "parameters": {
                        "cdStorageAccount": {
                            "type": "string"
                        },
                        "cdStorageAccountSASToken": {
                            "type": "string"
                        },
                        "nestedTemplateSuffix": {
                            "type": "string"
                        },
                        "resourceGroupName": {
                            "type": "string"
                        },
                        "roleAssignment": {
                            "type": "object"
                        },
                        "runAsIdentity": {
                            "type": "string"
                        },
                        "iterator": {
                            "type": "string"
                        },
                        "now": {
                            "type": "string",
                            "defaultValue": "[utcNow('u')]"
                        }
                    },
                    "variables": {
                        "nameGuid": "[guid(concat(subscription().subscriptionId, '-', parameters('resourceGroupName'), '-', parameters('roleAssignment').name))]",
                        "Contributor": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
                        "Reader": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]"
                    },
                    "resources": [
                        {
                            "name": "[concat('-deploymentScript-getPrincipalId', '-', parameters('iterator'), '-', parameters('nestedTemplateSuffix'))]",
                            "type": "Microsoft.Resources/deploymentScripts",
                            "apiVersion": "2020-10-01",
                            "identity": {
                                "type": "UserAssigned",
                                "userAssignedIdentities": {
                                    "[parameters('runAsIdentity')]": {}
                                }
                            },
                            "location": "westeurope",
                            "kind": "AzurePowerShell",
                            "properties": {
                                "azPowerShellVersion": "5.6",
                                "cleanupPreference": "Always",
                                "primaryScriptUri": "[concat(parameters('cdStorageAccount'), '/', 'scripts/Get-PrincipalId.ps1', parameters('cdStorageAccountSASToken'))]",
                                "arguments": "[concat('-PrincipalName ', parameters('roleAssignment').name, ' -PrincipalType ', parameters('roleAssignment').principalType)]",
                                "forceUpdateTag": "[parameters('now')]",
                                "retentionInterval": "PT1H",
                                "timeout": "PT15M"
                            }
                        },
                        {
                            "name": "[variables('nameGuid')]",
                            "type": "Microsoft.Authorization/roleAssignments",
                            "apiVersion": "2020-04-01-preview",
                            "dependsOn": [
                                "[resourceId('Microsoft.Resources/deploymentScripts', concat('-deploymentScript-getPrincipalId', '-', parameters('iterator'), '-', parameters('nestedTemplateSuffix')))]"
                            ],
                            "properties": {
                                "roleDefinitionId": "[variables(parameters('roleAssignment').builtInRoleType]",
                                "principalId": "[reference(concat('-deploymentScript-getPrincipalId', '-', parameters('iterator'), '-', parameters('nestedTemplateSuffix'))).outputs.principalId]",
                                "principalType": "[parameters('roleAssignment').principalType]"
                            }
                        }
                    ],
                    "outputs": {}
                }
            }
        }
    ],
    "outputs": {}
}

The one concern you have to realize is the time penalty of this approach. Because deployment scripts have to create and destroy storage accounts and container instances it will not be quick. During my tests I measured execution times between 2 and 4 minutes. If you want to have quick deployments stick to the use of manual looking up principal ids in upfront and passing them in as parameters.

Comments

Popular posts from this blog

CS8357: The specified version string contains wildcards, which are not compatible with determinism.

Today I was busy with creating a WCF service solution in Visual Studio Enterprise 2017 (15.9.2). In this solution I use a few C# class libraries based on .NET 4.7.2. When I compiled the solution I got this error message: Error CS8357: The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation The error message is linking to my AssemblyInfo.cs file of the Class library projects. In all the projects of this solution I use the wildcard notation for generating build and revision numbers. // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0....

Assign an existing certificate to your IIS website with WiX

Recently I had to change the bindings of existing IIS hosted websites and APIs from HTTP to HTTPS. They are installed with a MSI file created with the WiX Toolset . Because I have to use an already on the server installed certificate I cannot use the Certificate element from the IIS Extension because this element only supports installing and uninstalling certificates based on PFX files. After doing some research I found the blog article Assign Certificate (Set HTTPS Binding certificate) to IIS website from Wix Installer which described the usage of Custom Actions for this purpose. I adopted this approach and rewrote the code for my scenario. With WiX I still create the website. <iis:WebSite Id="WebSite" ConfigureIfExists="yes" AutoStart="yes" Description="MyWebsite" Directory="IISROOT" StartOnInstall="yes"> <iis:WebAddress Id="WebSite...

Fixing HTTP Error 401.2 unauthorized on local IIS

Sometimes the Windows Authentication got broken on IIS servers so you cannot log in locally on the server. In that case you get the dreadfully error message HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers. To fix this issue you can repair the Windows Authentication feature with the following PowerShell commands: Remove-WindowsFeature Web-Windows-Auth Add-WindowsFeature Web-Windows-Auth