Home / Azure

AzureRunbookAdvanced

RoleAssignmentLimitExceeded: clean up orphaned and redundant Azure role assignments before the subscription runs out

Deployments fail with RoleAssignmentLimitExceeded. Count assignments per subscription, remove orphaned ones from deleted identities, consolidate duplicates into groups and stop the count creeping back up.

Deepak Bhardwaj7 min read

Applies toAzure RBAC (Azure Resource Manager), Azure Resource Graph, Microsoft Graph v1.0, Azure CLI 2.x, Az PowerShell

A pipeline, a Bicep deployment or a portal user tries to grant access and gets:

No more role assignments can be created (code: RoleAssignmentLimitExceeded)

The subscription has hit its role assignment limit. Microsoft documents this limit as fixed: support can't raise it, so you have to delete assignments. At the time of writing the RBAC limits page lists 5,000 per subscription and 500 per management group. Check the current limits page before you plan around a number.

Assignments at subscription, resource group and resource scope count towards the subscription limit. Assignments at management group scope, PIM-eligible assignments and assignments scheduled for the future don't.

Caution

Every step below removes access. Export the full list of assignments first and get the deletions approved. Removing the wrong assignment from a managed identity or pipeline causes a 401/403 outage that looks unrelated to this clean-up.

Step 1: Confirm the count and export a backup

Count assignments per subscription across the tenant with Resource Graph:

az graph query -q "
authorizationresources
| where type =~ 'microsoft.authorization/roleassignments'
| where id startswith '/subscriptions'
| extend subscriptionId = tostring(split(id, '/')[2])
| summarize assignments = count() by subscriptionId
| order by assignments desc" --first 100 -o table

For a single subscription, PowerShell gives the same number the limit uses:

$scope = "/subscriptions/<subscription-id>"
$ras = Get-AzRoleAssignment -Scope $scope | Where-Object { $_.Scope.StartsWith($scope) }
$ras.Count

The StartsWith filter drops assignments inherited from management groups, which don't count.

Export everything before you change anything:

$ras | Select-Object RoleAssignmentId, RoleDefinitionName, RoleDefinitionId, ObjectId, ObjectType, DisplayName, Scope, Condition |
  Export-Csv ".\ra-backup-$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation

This file is your rollback plan. Each row has the role, principal and scope you need to recreate an assignment.

Step 2: Remove orphaned assignments

When a user, group, service principal or managed identity is deleted, its role assignments stay behind. They still count towards the limit. Pipelines that create short-lived managed identities or service principals for each run are the usual source of thousands of them.

The portal shows these as Identity not found. Az PowerShell returns ObjectType as Unknown, and the Azure CLI returns an empty principalName:

$orphans = $ras | Where-Object { $_.ObjectType -eq "Unknown" }
$orphans | Group-Object RoleDefinitionName | Sort-Object Count -Descending | Select-Object Count, Name
az account set --subscription <subscription-id>
az role assignment list --all \
  --query "[?principalName=='' && starts_with(scope, '/subscriptions/')].{id:id, role:roleDefinitionName, scope:scope, principalId:principalId}" -o table

Unknown can also mean the caller couldn't read the directory, for example a service principal without Microsoft Graph read permissions. Run this as an identity that can read users, groups and service principals. If you see thousands of Unknown objects at once, check directory read access before deleting anything.

Double-check against Microsoft Graph

Resource Graph stores the principalType from when the assignment was created and doesn't update it when the principal is deleted. To prove a principal is gone, resolve the IDs in Microsoft Graph. getByIds returns only the objects that still exist:

cat > ids.json <<'EOF'
{ "ids": ["<principal-id-1>", "<principal-id-2>"], "types": ["user","group","servicePrincipal"] }
EOF

az rest --method post \
  --url "https://graph.microsoft.com/v1.0/directoryObjects/getByIds" \
  --headers "Content-Type=application/json" \
  --body @ids.json \
  --query "value[].id" -o tsv

Any ID you sent that isn't in the response no longer exists in the tenant. The request accepts a limited number of IDs per call (check the Graph documentation), so send them in batches.

Delete the orphans

foreach ($ra in $orphans) {
  Remove-AzRoleAssignment -InputObject $ra -WhatIf
}

Read the -WhatIf output, then run it again without -WhatIf. With the CLI you can pass a list of IDs:

az role assignment delete --ids <assignment-id-1> <assignment-id-2>

Tip

A soft-deleted user can be restored from the Entra ID recycle bin for a limited time. If that might be needed, wait until the restore window has passed before deleting their orphaned assignments, or keep the backup CSV so you can recreate them.

Step 3: Consolidate duplicates and redundant scopes

Orphans are often not enough. These queries come from Microsoft's RBAC limits guidance. Run them in Resource Graph Explorer with the authorization scope set to At, above and below, or with az graph query.

Same role, same scope, many principals: replace with a group

authorizationresources
| where type =~ "microsoft.authorization/roleassignments"
| where id startswith "/subscriptions"
| extend RoleId = tolower(tostring(properties.roleDefinitionId))
| join kind = leftouter (
    authorizationresources
    | where type =~ "microsoft.authorization/roledefinitions"
    | extend RoleDefinitionName = tostring(properties.roleName)
    | extend RoleId = tolower(id)
    | project RoleDefinitionName, RoleId
  ) on $left.RoleId == $right.RoleId
| extend principalId = tostring(properties.principalId)
| extend principal_to_ra = pack(principalId, id)
| summarize count_ = count(), AllPrincipals = make_set(principal_to_ra)
    by RoleDefinitionId = RoleId, Scope = tolower(properties.scope), RoleDefinitionName
| where count_ > 1
| order by count_ desc

Fifty users each holding Reader on the same resource group become one group assignment:

GROUP_ID=$(az ad group create --display-name "grp-rg-app-readers" \
  --mail-nickname grp-rg-app-readers --query id -o tsv)

az ad group member add --group $GROUP_ID --member-id <user-object-id>   # repeat per member

az role assignment create --assignee-object-id $GROUP_ID --assignee-principal-type Group \
  --role Reader --scope /subscriptions/<sub-id>/resourceGroups/rg-app

Have the users sign in again (or wait for new tokens) and confirm they still have access. Then delete their individual assignments.

Warning

Don't move managed identities into groups as part of this. Managed identity tokens are cached and can take a long time to pick up new group membership, so a workload can lose access between deleting its direct assignment and its token refresh. Leave direct assignments for workload identities, and consolidate the human ones.

Same role and principal at several scopes

authorizationresources
| where type =~ "microsoft.authorization/roleassignments"
| where id startswith "/subscriptions"
| extend RoleDefinitionId = tolower(tostring(properties.roleDefinitionId))
| extend PrincipalId = tolower(properties.principalId)
| summarize count_ = count(), Scopes = make_set(tolower(properties.scope)) by RoleDefinitionId, PrincipalId
| where count_ > 1
| order by count_ desc

If a principal has Contributor on a resource group and on several resources inside it, the resource-level assignments add nothing. Remove them. Check for ABAC conditions first (properties.condition), because an assignment with a condition isn't a duplicate of one without.

Same principal and scope, several built-in roles

A principal holding Storage Blob Data Reader, Key Vault Secrets User and Monitoring Reader on one resource group can use a single custom role with the same actions instead. That saves assignments, but custom roles are a tenant-wide limit too and need maintenance. Use them for the large, repeated patterns, not one-offs.

Step 4: Verify

(Get-AzRoleAssignment -Scope $scope | Where-Object { $_.Scope.StartsWith($scope) }).Count

Rerun the failed deployment. Watch for 401/403 errors over the next day:

AzureActivity
| where TimeGenerated > ago(24h)
| where ActivityStatusValue == "Failure"
| where Properties has "AuthorizationFailed"
| summarize failures = count() by Caller, OperationNameValue
| order by failures desc

If a caller you touched appears here, recreate its assignment from the backup CSV.

Other options

Option When it helps
PIM eligible assignments Standing admin and operator access. Eligible assignments don't count towards the limit. Requires Microsoft Entra ID P2 or Governance licensing
Assign at management group scope Broad roles (Reader, Security Reader) that apply to many subscriptions. They count towards the separate management group limit
Split the subscription One subscription hosts many teams or tenants. Move workloads into their own subscriptions

Prevent it next time

  • Alert on the count. Schedule the Resource Graph count query in an Automation runbook or Logic App and warn at around 80% of the limit.
  • Delete role assignments before or together with the identity. In Bicep, deploy identities and their role assignments in one deployment stack so deleting the stack removes both.
  • Stop creating a new managed identity or service principal per pipeline run. Reuse a small set of deployment identities.
  • Grant human access through groups and PIM, not to individual users.
  • Run the orphan query monthly and delete what it finds.