Posted in:

The more I use Azure the more often I find myself needing to assign various managed identities / service principals to various groups and roles, and while that can be done in the Portal, it's cumbersome and I'd prefer to automate it.

So in this post I'll sharing a few Azure CLI commands that should prove useful whenever you're configuring Service Principals.

Getting a service principal's object id

Suppose you know the name of the service principal, but not the "object id", which is required for assigning it to groups and roles. You can use a filter with the az ad sp list command to find that service principal and then a query to pick out just the object id.

Note that you should avoid trying to use the query parameter to find the matching name, as that will likely not find it as it only applies to the first page of results.

$spName = "my-sp-name"
$objectId = az ad sp list --filter "displayname eq '$spName'" `
            --query "[0].id" -o tsv

Note that the object id is different from the app id. If you do need the app id for any reason you just need to change the query parameter:

$appId = az ad sp list --filter "displayname eq '$spName'" `
            --query "[0].appId" -o tsv

Adding to a group

Suppose we want to add the service principal to a group. We need the group id to do that, and if we need to look it up, we can do so with the az ad group list command and using a filter.

$groupName = "my group"
$groupId = az ad group list --filter "displayname eq '$groupName'" `
                --query "[].id" -o tsv

Then the az ad group member add command allows us to add the object id of our service principal to the group.

az ad group member add --group $groupId --member-id $objectId

Creating a role assignment

If we want to create a role assignment, then as well as knowing the user we're assigning the role to and the name of the role, we also need to provide a "scope" for that to apply to. This is typically a long / delimited path to an Azure resource. So for a KeyVault it might look like this:

/subscriptions/082b5b37-4be8-4e36-a6a9-f4f395beb56c/resourceGroups/my-resource-group/providers/Microsoft.KeyVault/vaults/my-keyvault-name

You can of course construct this string yourself, but actually this is quite often just the "ID" of the resource as returned by the Azure CLI. So we could get the above value with the following command:

$keyVaultScope = az keyvault show -n $keyVaultName -g $keyVaultGroup `
                    --query id -o tsv

And now that we have the scope, we can simply use the az role assignment create to assign the role to our service principal, and we can pass the role name directly (in this example it's "Key Vault Administrator"):

az role assignment create --assignee "$objectId" `
    --role "Key Vault Administrator" `
    --scope "$keyVaultScope"

Hope this proves useful to you.

Want to learn more about the Azure CLI? Be sure to check out my Pluralsight course Azure CLI: Getting Started.