Skip to content

Instantly share code, notes, and snippets.

@AlexFilipin
Last active September 20, 2023 22:31
Show Gist options
  • Save AlexFilipin/daace2f2d7989545e8ab0b969de2aaed to your computer and use it in GitHub Desktop.
Save AlexFilipin/daace2f2d7989545e8ab0b969de2aaed to your computer and use it in GitHub Desktop.
Azure Automation Managed Identity Graph Access
# Assign Graph application permissions to managed identity (outside of Azure Automation)
$spID = "c3bfc803-bc8a-47af-a8a4-eed98dce8bca" #Managed Identity SP
$PermissionName = "User.Read.All"
$GraphServicePrincipal = Get-MgServicePrincipal -Filter "startswith(DisplayName,'Microsoft Graph')" | Select-Object -first 1 #Graph App ID: 00000003-0000-0000-c000-000000000000
$AppRole = $GraphServicePrincipal.AppRoles | Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}
New-MgServicePrincipalAppRoleAssignment -AppRoleId $AppRole.Id -ServicePrincipalId $spID -ResourceId $GraphServicePrincipal.Id -PrincipalId $spID
$AppRoleAssignments = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $spID
# Please note you can also give an managed identity permissions via:
# Role assignments, such as User Administrator scoped to an Administrative Unit
# Ownership, such as owner of a group to manage the membership with the MI
# This can be done via UI and in many cases allows you to better follow the concept of least privilege
# Connect to Microsoft Graph within Azure Automation (Microsoft Graph PowerShell v1)
Connect-AzAccount -Identity
$token = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com"
Connect-MgGraph -AccessToken $token.Token
# Connect to Microsoft Graph within Azure Automation (Microsoft Graph PowerShell v2 - see https://devblogs.microsoft.com/microsoft365dev/microsoft-graph-powershell-v2-is-now-in-public-preview-half-the-size-and-will-speed-up-your-automations/)
# System-assigned managed identity
Connect-MgGraph -Identity
# User-assigned managed identity
Connect-MgGraph -Identity -ClientId "User_Assigned_Managed_identity_Client_Id"
# More detailed blog from https://twitter.com/JefTek - https://cloudid.space/ms-graph-sdk-powershell-v2-and-azure-automation/
@helplessJ
Copy link

Cool thank you Alex. 🫡

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment