Search code examples
azurepowershellazure-managed-identityazure-service-principalazure-identity

Can't assign Directory Readers role to managed identity using Az PowerShell: "Role Not Found" Error


I'm working on connecting to Microsoft Graph using a User Managed Identity (UMI). I've already created the managed identity in the Azure portal, but now I need to assign Directory Readers role to this identity using PowerShell to retrieve directory objects information.

I tried using New-AzRoleAssignment -ObjectId 'xxxxxxxxx' -RoleDefinitionName "Directory Reader" -Scope '/' but it's failing with New-AzRoleAssignment: Cannot find role definition with name 'Directory Readers' error

The Directory Readers role is visible in the Azure portal and can be assigned manually, but it’s not found in PowerShell.

How can the Directory Readers role be assigned to a managed identity using Az PowerShell? Is this possible, or is something being overlooked?


Solution

  • Note that, New-AzRoleAssignment cmdlet is used for Azure RBAC roles but "Directory Readers" is Microsoft Entra Role.

    Initially, I too got same error when I ran your command in my environment like this:

    New-AzRoleAssignment -ObjectId 'msiID' -RoleDefinitionName "Directory Reader" -Scope '/'
    

    Response:

    enter image description here

    To resolve the error, switch to Microsoft Graph PowerShell module by running below commands to assign "Directory Readers" role to managed identity service principal:

    Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory"
    
    $roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -Filter "DisplayName eq 'Directory Readers'"
    $managedIdentity = Get-MgServicePrincipal -Filter "DisplayName eq 'msiname'"
    
    New-MgRoleManagementDirectoryRoleAssignment -DirectoryScopeId '/' -RoleDefinitionId $roleDefinition.Id -PrincipalId $managedIdentity.Id
    

    Response:

    enter image description here

    To confirm that, I checked the same in Portal where "Directory Readers" role assigned successfully to managed identity service principal like this:

    enter image description here