On a recent project, I needed a reliable and repeatable method of creating Azure AD service principles for use with Azure DevOps and Azure Sentinel, among other things. I also needed to apply Azure roles to these service principles at different levels of the hierarchy, be that root management group, sub management group or subscription. All examples assume that the az module is already installed.
Create the service principle:
For the SP that I created for the DevOps team, I needed to give it the Owner role at the root level:
New-AzRoleAssignment -ObjectId “<ObjectIDOfSP>” -Scope “/” -RoleDefinitionName “Owner”
Additionally, I discovered that if you delete a SP prior to removing its roles, you end up with orphaned references in the resource level role assignments. Where these were inherited from the root level and I had no GUI visibility of that level, I had to use PowerShell to tidy up. Assuming that you don’t have a record of the ObjectID of the deleted SP, get all role assignments with:
Get-AzRoleAssignment | Select-Object -Property DisplayName, ObjectID, RoleDefinitionName, Scope
Find the object whose scope is “/” , role is Owner and has no DisplayName. That is the orphaned object, grab the ObjectID and remove with:
AzRoleAssignment -ObjectId “<ObjectIDOfSP>” -Scope “/”