Last active
August 6, 2022 13:27
-
-
Save garrytrinder/6352326eadbc9d00e808022ec724188e to your computer and use it in GitHub Desktop.
Add AppRole Assignment to Service Principal using Azure CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Assign Application Role to Azure Active Directory service principal | |
| .DESCRIPTION | |
| This script helps assign Application Roles from existing resources to Azure Active Directory service principals, useful for assigning roles to Managed Identity service principals which cannot be performed through the Azure Portal | |
| .PARAMETER ResourceName | |
| The name of the service principal that has the app role that you want to assign | |
| .PARAMETER AppRoleName | |
| The name of the app role that you want to assign | |
| .PARAMETER PrincipalName | |
| The name of the service principal that you want to assign the app role to | |
| .PARAMETER TenantDomain | |
| The domain name of the target tenant | |
| .EXAMPLE | |
| Add-AppRoleAssignment.ps1 -ResourceName "Microsoft Graph" -AppRoleName "Group.ReadWrite.All" -PrincipalName "func-automation-prod" -TenantDomain "contoso.com" | |
| Assign the Microsoft Graph app role Group.ReadWrite.All to the func-automation-prod service principal in the contoso.com tenant | |
| #> | |
| [CmdletBinding()] | |
| param ( | |
| [Parameter(Position = 0, Mandatory = $true)] | |
| [string] | |
| $ResourceName, | |
| [Parameter(Position = 1, Mandatory = $true)] | |
| [string] | |
| $AppRoleName, | |
| [Parameter(Position = 2, Mandatory = $true)] | |
| [string] | |
| $PrincipalName, | |
| [Parameter(Position = 3, Mandatory = $true)] | |
| [string] | |
| $TenantDomain | |
| ) | |
| $ErrorActionPreference = 'Stop' | |
| $Resource = az ad sp list --display-name $ResourceName --query "{ AppRoleId: [0] .appRoles [?value=='$AppRoleName'].id | [0], ObjectId:[0] .objectId }" -o json | ConvertFrom-Json | |
| $Principal = az ad sp list --display-name $PrincipalName --query "{ ObjectId: [0] .objectId }" -o json | ConvertFrom-Json | |
| $Body = @{ | |
| "id" = $Resource.AppRoleId; | |
| "principalId" = $Principal.ObjectId; | |
| "resourceId" = $Resource.ObjectId | |
| } | ConvertTo-Json -Compress | |
| $Body = $Body.Replace('"', '\"') | |
| az rest -m post -u "https://graph.windows.net/$TenantDomain/servicePrincipals/$($Principal.ObjectId)/appRoleAssignments?api-version=1.6" -b "$Body" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment