Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save starkfell/b077951b233b6febbed9b0c62e5e6e35 to your computer and use it in GitHub Desktop.
Save starkfell/b077951b233b6febbed9b0c62e5e6e35 to your computer and use it in GitHub Desktop.
Delete Role Assignments for deleted or non-existing Managed Identities, Service Principals, Groups, and Users
#!/bin/bash
: '
Name: cleanup-role-assignments-for-non-existing-principals.sh
Author: Ryan Irujo
Description: This scripts is for resolving the issue in the article below.
https://learn.microsoft.com/en-us/answers/questions/672875/azure-managed-identity-role-assignment-is-not-dele
Additional Notes: Use this script with caution!
If you want to review all of your entries before removing them
I recommend running the query below which will generate a table format for your perusal.
az role assignment list \
--all \
--query "[?principalName==''].{roleDefinitionName:roleDefinitionName, principalId:principalId, principalType:principalType, scope:scope, id:id}" \
--output table > roleAssignmentsToRemove.txt
'
environments="dev val"
for envName in $environments
do
# Retrieving all Role Assignments across the entire Subscription where the [PrincipalName] field is empty.
# This, in almost all cases, means the principal (User, Service Pricipal, Managed Idenity) no longer exists.
echo "Checking for Role Assignments to remove in the [$envName] Environment."
az role assignment list \
--all \
--query "[?principalName==''].{roleDefinitionName:roleDefinitionName, principalId:principalId, principalType:principalType, scope:scope, id:id}" \
--output json > roleAssignmentsToRemove.json && \
echo "Retrieved all Role Assignments that no longer have a Principal associated with them."
# Making all JSON entry groups into single-line entries for easier processing.
roleAssignments=$(cat roleAssignmentsToRemove.json | jq -c '.[]')
echo "Processing Role Assignments in [$envName]."
while read -r entry
do
roleDefinitionName=$(echo "$entry" | jq -r .roleDefinitionName)
principalId=$(echo "$entry" | jq -r .principalId)
principalType=$(echo "$entry" | jq -r .principalType)
roleAssignmentId=$(echo "$entry" | jq -r .id)
scope=$(echo "$entry" | jq -r .scope)
# Removing all Role Assignments for Deleted Managed Identities related to the Azure Resources.
if [[ $scope == *"$envName"* ]]; then
az role assignment delete \
--ids "$roleAssignmentId" \
--output none && \
echo "Deleted [$roleDefinitionName] for [$principalId] of Principal Type [$principalType] for [$scope]."
fi
done <<< "${roleAssignments}"
echo ""
echo "Removal of Role Assigments in [$envName] is complete."
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment