Removing IAM Assignments - Unable to find identity

Dave O'Donohoe 170 Reputation points
2023-08-18T08:44:53.1233333+00:00

Hi,

We have circa 200 subscriptions, organised via management groups, with a lot of IAM assignments at various levels.

The problem - there are a lot of nonexisting / legacy objects, which I'd like to clean-up / remove RBAC assignments.

Identity not found.

Unable to find identity

Could anyone recommended a method were I could possibly script / automate this process, rather than having to browse to every subscription to manually remove IAM assignments to these phantom objects?

I would assume powershell would have this capability?

Thanks.

Microsoft Security | Microsoft Entra | Microsoft Entra ID
{count} votes

Accepted answer
  1. James Hamil 27,221 Reputation points Microsoft Employee Moderator
    2023-08-21T21:43:49.8066667+00:00

    Hi @Dave O'Donohoe , you can try something like this in PowerShell. Let me know if it works:

    # Connect to your Azure account
    Connect-AzAccount
    
    # Get all subscriptions
    $subscriptions = Get-AzSubscription
    
    # Loop through each subscription
    foreach ($subscription in $subscriptions) {
        # Set the current subscription context
        Set-AzContext -SubscriptionId $subscription.Id
    
        # Get all role assignments
        $roleAssignments = Get-AzRoleAssignment
    
        # Loop through each role assignment
        foreach ($roleAssignment in $roleAssignments) {
            try {
                # Try to get the assigned identity (user, group, service principal, or managed identity)
                Get-AzADObject -ObjectId $roleAssignment.ObjectId -ErrorAction Stop
            } catch {
                # If the assigned identity is not found, remove the role assignment
                if ($_.Exception.Message -like "*Unable to find identity*") {
                    Remove-AzRoleAssignment -ObjectId $roleAssignment.ObjectId -RoleDefinitionName $roleAssignment.RoleDefinitionName -Scope $roleAssignment.Scope -Force
                }
            }
        }
    }
    

    This script connects to your Azure account, retrieves all subscriptions, and iterates through each subscription to get all role assignments. For each role assignment, it checks if the assigned identity exists. If the identity is not found, the script removes the role assignment.

    Please let me know if you have any questions and I can help you further.

    If this answer helps you please mark "Accept Answer" so other users can reference it.

    Thank you,

    James


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.