This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
List Azure role assignments using Azure CLI
- 7 contributors
Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To determine what resources users, groups, service principals, or managed identities have access to, you list their role assignments. This article describes how to list role assignments using Azure CLI.
If your organization has outsourced management functions to a service provider who uses Azure Lighthouse , role assignments authorized by that service provider won't be shown here. Similarly, users in the service provider tenant won't see role assignments for users in a customer's tenant, regardless of the role they've been assigned.
Prerequisites
- Bash in Azure Cloud Shell or Azure CLI
List role assignments for a user
To list the role assignments for a specific user, use az role assignment list :
By default, only role assignments for the current subscription will be displayed. To view role assignments for the current subscription and below, add the --all parameter. To include role assignments at parent scopes, add the --include-inherited parameter. To include role assignments for groups of which the user is a member transitively, add the --include-groups parameter.
The following example lists the role assignments that are assigned directly to the [email protected] user:
List role assignments for a resource group
To list the role assignments that exist at a resource group scope, use az role assignment list :
The following example lists the role assignments for the pharma-sales resource group:
List role assignments for a subscription
To list all role assignments at a subscription scope, use az role assignment list . To get the subscription ID, you can find it on the Subscriptions blade in the Azure portal or you can use az account list .
List role assignments for a management group
To list all role assignments at a management group scope, use az role assignment list . To get the management group ID, you can find it on the Management groups blade in the Azure portal or you can use az account management-group list .
List role assignments for a managed identity
Get the principal ID of the system-assigned or user-assigned managed identity.
To get the principal ID of a user-assigned managed identity, you can use az ad sp list or az identity list .
To get the principal ID of a system-assigned managed identity, you can use az ad sp list .
To list the role assignments, use az role assignment list .
By default, only role assignments for the current subscription will be displayed. To view role assignments for the current subscription and below, add the --all parameter. To view inherited role assignments, add the --include-inherited parameter.
- Assign Azure roles using Azure CLI
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .
Submit and view feedback for
Additional resources
- CreatingAServicePrincipal
If you just want to get started asap with a service principal and azure with a client secret and permissive RBAC settings, then just run the following commands (redacted as required)
Why use a Service Principal anyways
When it comes to running some commands adhoc off the command line, a human user account based on a user principal account is fine. But for any serious use case, this would not qualify as a sustainable devops practice. Typically this is done by calling the az login command from a terminal which invokes a web-based login process in the background. For automation, a service principal account is required to run tasks such as:
- Continuous Integration tasks (eg blob storage access)
- Continuous Deployment tasks (eg deployment of a vm)
- Infrastructure as Code Deployments (eg using terraform)
- Running scheduled tasks
- Accessing Azure Key vault or Azure Blob storage from a running application in application code using the Azure SDKs
Anatomy of a Service Principal
A service principal does not exist in isolation. In fact, a service principal is a 'security principal' or identity that represents an active directory application in a given tenant. By default, a security principal will be created in the default tenant along with the application object. As azure active directory is multi-tenant, further service principals can be created for additional tenants should the requirement arise.
Service Principal and authentication
Authentication with a service principal can be through using
- A client secret
- A client certificate (X.509 self-signed certificate)
Generally, I prefer the creation of an azure service principal with a client certificate which has been self-signed.
From a security perspective, it is vital to keep both secrets and certificates secure. This can be done by encrypting the data with mozilla sops .
Azure Terraform Provider
Terraform is a highly declarative language for defining infrastructure and I normally prefer it for creating all kinds of infrastructure.
Terraform still requires a service principal to get started - chicken and egg situation.
The service principal for the azuread_service_principal terraform module requires the User Account Administrator role. From a security perspective, using such a highly priveleged service principal requires careful scrutiny.
Creating an Azure Application
Prerequisites.
- Azure CLI - The installation instructions of az cli on ubuntu can be found here
Login with a user principal
This will return the following information revealing the user, default tenant and default subscription information.
Ensure the Correct Azure Subscription is selected
If you need to use a specific subscription other than the default one when logged in, it can be set as follows
Note: You can check what subscriptions are available by running az account list .
Create the azure application
Docs for az ad app create
The extract below shows some of the important fields from the http response including the appId and objectId .
Note: You can check what apps are already created by running
Creating the Service Principal
The service principal is created next and associated with the previously created app. The appId or objectId can be used to assign the service principal
Docs for az ad spn create
Extract from the json response:
Credentials creation with a client secret
So far no credentials have been created for the service principal. Let's take a look...
Docs for az ad sp credential list
The response is an empty list which confirms roles are not yet assigned
Create new credentials with a client secret
The response is as follows:
Once these credentials are returned, you will need to store them somewhere secure for later retrieval, ideally, in an encrypted format.
Running the following command again will reveal the credentials:
Note: If you are a user of terraform azure provider , the credentials above correspond to the following naming in terraform:
Credentials creation with a client certificate
Creating a certificate using the azure cli.
The easy way to do this is to have the azure cli create a certificate for you. Let's append new credentials by creating a public cert and private key with the azure cli.
Note: With the --append argument, the previous secret based credentials will not be overridden. Omit --append if you want to use a client certificate only and override previous credentials.
The output is as follows:
The value for fileWithCertAndPrivateKey contains the path to the public certificate and the private key. This file should be stored somewhere safely and ideally in an encrypted format. It is the key to the kingdom. Although, we will be reducing the dominion of that kingdom later by employing RBAC and setting roles on the service principal.
Creating a certificate with your own certificate authority
You can also create your own certificate and private key using your own certificate authority for creating the service principal credentials.
In this guide, I will create a certificate authority to create the azure service principal certificate. If you already have your own certificate authority then you can skip this step. Basically, this means using your own PKI (public key infrastructure).
You can keep the files ca.pem and ca-key.pem for further uses of as your certificate authority. The ca-key.pem is the private key ancd should be kept very safe, ideally in an encrypted format.
The next step is to create the new service principal private key and certificate
As a result of running the last command, a private key file cert-key.pem and public cert cert.pem will be generated. Be sure to store these files away, in a safe location, ideally encrypted. Azure requires having these two files concatenated together to login as a service principal. The login process is demonstrated later
Now we are ready to create the service principal with the self-signed certificate as follows:
Given the complexity of creating your own public key infrastructure and generating the certs, it is probably easier to just create a certificate using the azure cli as outlined earlier .
Roles assignment and RBAC
Role Based Access Control allows devops and software engineers to create service principals following the least privilege principle. Here are two ways to approach assigning roles to an azure service principal:
- Assign built-in roles
- Assign a custom role definition
After the service principal has been associated to the app in the default tenant, no roles have yet been assigned to the service principal. Roles are the way in which access control works in Azure. Let's take a look at the roles assigned so far.
Docs for az role assignment list
Assigning a built-in role to a service principal
The Contributor built-in role is highly permissive - avoid using it when possible. It would be better to assign the minimal roles necessary. For example, if an application only requires read access to an azure blob storage container, then the Storage Blob Data Reader is all that is required. Assigning multiple restrictive built-in roles is also possible and better than applying the highly permissive Contributor role.
The --scope argument allows one to reduce the access levels of the service principal even further. It can be restricted to specific subscription(s) and even more fine grained to specific resource group(s).
By using a sensible combination of roles and scopes, the overall security of operations in the cloud is enhanced. In the unlikely event that a service principal becomes comprimised, the potential for malicious activitty is reduced to the smallest range of resources.
Assigning a custom role definition to a service principal
An entirely custom role can be built up from scratch and assigned to a service principal. This is a very powerful approach to RBAC for a service principal because it gives the cloud operator fine-grained control of what permissions are granted.
Once the credentials creation step and rbac assignment steps are complete, the service principal is then ready to use and it can be tested to verify that it is working correctly.
While still logged in as a user principal, you can get set some of the variables in the terminal before running an azure logout.
At this stage, logout with your user principal account.
Logging in with a client secret
Logging in with an azure generated client cert.
When you ran the az cli command to create credentials to a client cert as outlined in above , the json response included a key pair "fileWithCertAndPrivateKey": "<path_to_pem>" . This file path contains the private key and public certificate in a single file.
To login, just pass the file path in the password field of the az login command as follows:
Logging in with a self-signed client cert
Assuming that cert-key.pem is the private key and cert.pem is the public certificate, azure requires that those certs are concatenated into a single file and the path of the newly created concatenated cert file passed in the password field for login.
Now that you have your service principal setup, it's time to use it for some terraform automation.
Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Manage Azure Role Assignments Like a Pro with PowerShell
Today’s blog post is a little bit different. I have a couple of examples of how you can use PowerShell snippets and simple commandlets to get or set role assignmnets in your Azure Subscriptions.
PowerShell examples for managing Azure Role assignments
List all role assignments in a subscription, get all role assignments for a specific resource group, get all role assignments for a specific user, add a role assignment to a user, remove a role assignment for a user, remove all role assignments for a specific user, list all built-in roles, list all custom roles, create a custom role, update a custom role, delete a custom role, list all users or groups assigned to a specific role, list all permissions granted by a specific role, list all resource groups that a user has access to, create a role assignment for a service principal, powershell script to manage azure role assignments.
And now there is a script that combines some of these examples into one usable function:
I hope this was useful. Let me know if you liked the format of this blog and if you want me to include more of these examples.
Vukasin Terzic
Recent Update
- Writing your first Azure Terraform Configuration
- Transition from ARM Templates to Terraform with AI
- Getting started with Terraform for Azure
- Terraform Configuration Essentials: File Types, State Management, and Provider Selection
- Dynamically Managing Azure NSG Rules with PowerShell
Trending Tags
Retrieve azure resource group cost with powershell api.
The Future Of Azure Governance: Trends and Predictions
Further Reading
In my previous blog posts, I wrote about how simple PowerShell scripts can help speed up daily tasks for Azure administrators, and how you can convert them to your own API. One of these tasks is...
Azure Cost Optimization: 30 Ways to Save Money and Increase Efficiency
As organizations continue to migrate their applications and workloads to the cloud, managing and controlling cloud costs has become an increasingly critical issue. While Azure provides a robust s...
Custom PowerShell API for Azure Naming Policy
To continue our PowerShell API series, we have another example of a highly useful API that you can integrate into your environment. Choosing names for Azure resources can be a challenging task. ...
COMMENTS
To list the role assignments for a specific user, use az role assignment list: Azure CLI. az role assignment list --assignee {assignee} By default, only role assignments for the current subscription will be displayed. To view role assignments for the current subscription and below, add the --all parameter.
Setup of Sample Resources. Create the test resource group. az group create --name ado-role-assignment-test-rg--location westus. Create the test storage account. az storage account create -n ...
. Azure provides four levels of scope: resource, resource group, subscription, and management group.It's a best practice to grant access with the least privilege that is needed, so avoid assigning a role at a broader scope.
If you just want to get started asap with a service principal and azure with a client. secret and permissive RBAC settings, then just run the following commands (redacted as required) app_display_name="<your_app_name>" subscription_id="<your_subscription_id>". az login. az account set -s "${subscription_id}"
To edit an existing role assignment condition, use az role assignment update and a JSON file as input. The following shows an example JSON file where condition and description are updated. Only the condition, conditionVersion, and description properties can be edited. You must specify all the properties to update the role assignment condition.
Learn how to manage Azure Role assignments using PowerShell snippets and simple commandlets. Discover examples for listing all role assignments, adding and removing assignments for users or service principals, creating custom roles, and more. Plus, check out a script that combines some of these examples into a single function. Written by Vukasin Terzic.
Let's start by just running this command and getting a list of all of the RBAC assignments: Get-AzRoleAssignment. Next, let's narrow that down so we are only looking for role assignments for one particular user. The Get-AzRoleAssignment command has a range of different parameters we can add which will act as a filter.
For future readers, if you tried to use Joy's answer to query for all roles assigned to a Managed Identity, and you're unexpectedly receiving an empty array, try adding the --all switch. EX: az role assignment list --assignee '<PRINCIPAL_ID>' --all. The relevant docs are here.