This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assign Azure roles using Azure CLI

  • 10 contributors

Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. This article describes how to assign roles using Azure CLI.

Prerequisites

To assign roles, you must have:

  • Microsoft.Authorization/roleAssignments/write permissions, such as Role Based Access Control Administrator
  • Bash in Azure Cloud Shell or Azure CLI

Steps to assign an Azure role

To assign a role consists of three elements: security principal, role definition, and scope.

Step 1: Determine who needs access

You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111 . You can get the ID using the Azure portal or Azure CLI.

For a Microsoft Entra user, get the user principal name, such as [email protected] or the user object ID. To get the object ID, you can use az ad user show .

For a Microsoft Entra group, you need the group object ID. To get the object ID, you can use az ad group show or az ad group list .

Service principal

For a Microsoft Entra service principal (identity used by an application), you need the service principal object ID. To get the object ID, you can use az ad sp list . For a service principal, use the object ID and not the application ID.

Managed identity

For a system-assigned or a user-assigned managed identity, you need the object ID. To get the object ID, you can use az ad sp list .

To just list user-assigned managed identities, you can use az identity list .

Step 2: Select the appropriate role

Permissions are grouped together into roles. You can select from a list of several Azure built-in roles or you can use your own custom roles. It's a best practice to grant access with the least privilege that is needed, so avoid assigning a broader role.

To list roles and get the unique role ID, you can use az role definition list .

Here's how to list the details of a particular role.

For more information, see List Azure role definitions .

Step 3: Identify the needed scope

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. For more information about scope, see Understand scope .

Resource scope

For resource scope, you need the resource ID for the resource. You can find the resource ID by looking at the properties of the resource in the Azure portal. A resource ID has the following format.

Resource group scope

For resource group scope, you need the name of the resource group. You can find the name on the Resource groups page in the Azure portal or you can use az group list .

Subscription scope

For subscription scope, you need the subscription ID. You can find the ID on the Subscriptions page in the Azure portal or you can use az account list .

Management group scope

For management group scope, you need the management group name. You can find the name on the Management groups page in the Azure portal or you can use az account management-group list .

Step 4: Assign role

To assign a role, use the az role assignment create command. Depending on the scope, the command typically has one of the following formats.

The following shows an example of the output when you assign the Virtual Machine Contributor role to a user at a resource group scope.

Assign role examples

Assign a role for all blob containers in a storage account resource scope.

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a storage account named storage12345 .

Assign a role for a specific blob container resource scope

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a blob container named blob-container-01 .

Assign a role for a group in a specific virtual network resource scope

Assigns the Virtual Machine Contributor role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a resource scope for a virtual network named pharma-sales-project-network .

Assign a role for a user at a resource group scope

Assigns the Virtual Machine Contributor role to [email protected] user at the pharma-sales resource group scope.

Assign a role for a user using the unique role ID at a resource group scope

There are a couple of times when a role name might change, for example:

  • You are using your own custom role and you decide to change the name.
  • You are using a preview role that has (Preview) in the name. When the role is released, the role is renamed.

Even if a role is renamed, the role ID does not change. If you are using scripts or automation to create your role assignments, it's a best practice to use the unique role ID instead of the role name. Therefore, if a role is renamed, your scripts are more likely to work.

The following example assigns the Virtual Machine Contributor role to the [email protected] user at the pharma-sales resource group scope.

Assign a role for all blob containers at a resource group scope

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at the Example-Storage-rg resource group scope.

Assign a role for an application at a resource group scope

Assigns the Virtual Machine Contributor role to an application with service principal object ID 44444444-4444-4444-4444-444444444444 at the pharma-sales resource group scope.

Assign a role for a new service principal at a resource group scope

If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you use a script to create a new managed identity and then try to assign a role to that service principal, the role assignment might fail. The reason for this failure is likely a replication delay. The service principal is created in one region; however, the role assignment might occur in a different region that hasn't replicated the service principal yet. To address this scenario, you should specify the principal type when creating the role assignment.

To assign a role, use az role assignment create , specify a value for --assignee-object-id , and then set --assignee-principal-type to ServicePrincipal .

The following example assigns the Virtual Machine Contributor role to the msi-test managed identity at the pharma-sales resource group scope:

Assign a role for a user at a subscription scope

Assigns the Reader role to the [email protected] user at a subscription scope.

Assign a role for a group at a subscription scope

Assigns the Reader role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a subscription scope.

Assign a role for all blob containers at a subscription scope

Assigns the Storage Blob Data Reader role to the [email protected] user at a subscription scope.

Assign a role for a user at a management group scope

Assigns the Billing Reader role to the [email protected] user at a management group scope.

  • List Azure role assignments using Azure CLI
  • Use the Azure CLI to manage Azure resources and resource groups

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

Assigning Service Principals to Groups and Roles with the Azure CLI

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 .

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:

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 .

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

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:

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:

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"):

Hope this proves useful to you.

Create and manage a Service Principal using the Azure CLI

This post explains how to create and how to manage a Service Principal using the Azure CLI

1. Introduction

A few weeks ago I started to learn about Github Actions , and my first goal was to create a simple workflow, that provisions a resource group on Azure using Terraform . I created a blank .yml file, and added the necessary steps until I needed to sign in to my Azure subscription. I was used to work with Azure DevOps for establishing CI/CD pipelines, and expected something similar to a Service connection of ADO to get access from the pipeline to the Azure subscription by using this very comfortable managed approach (see also one of my previous posts Build an Azure DevOps Pipeline using YAML for provisioning a Microservice in Azure with Terraform ). Now it was necessary to create a Service Principal for establishing the connection from the pipeline to my Azure subscription. I already created several Service Principals - but without taking a closer look at that concept. As I again had to deal with it, I’ve made my mind to get a better idea of it. Therefore, I also decided to write a blog post about it.

So, this blog post is intended to all who would like to start with creating, and managing a Service Principal on Azure using the Azure CLI

2. Prerequisites

  • Azure subscription

3. What is a Service Prinicial?

Before you can add, change, or delete resources on Azure , you have to sign in to your Azure subscription - for sure. So it’s clear that this is also mandatory, if you would like to achieve that in automated way - in my case by using pipelines. Without a successful login to an Azure subscription, specific e.g.: Terraform commands included in a GitHub Action would not work. You would never come to the idea of using the credentials of your fully privileged user in the pipeline code. So, if you would like to achieve the login to an Azure subscription in an automated way, by using e.g. pipelines, then you should use a Service Principal . It allows automated tools, applications or hosted services to conduct the Azure authentication, but the permissions are restricted in contrast to a user identity (e.g.: your fully privileged user). Providing the Service Principal only as much as necessary permissions is recommended. Consider therefore carefully which role and which scope you set.

learn.microsoft.com - create Azure Service Principal

4. Create and manage a Service Principal

4.1 login to your azure subscription.

The authentication to Azure has to done before a Service Principal can be created: in VS Code that’s conducted by opening a new Terminal and entering the following command:

A browser session will be opened, and an account has to be chosen, which will be used for the login. After confirming the credentials, the logs should be similar to those in the picture below:

01_az-login

In addition, ensure that the right subscription is used. The subscription can be changed by using the following command:

learn.microsoft.com - manage Azure scubscriptions with Azure CLI

4.2 Create a Service Principal

As a next step, the Service Principal has to be created. Following command is used to create a Service Principal named “AZ_SP_AZUREWORKSHOP_PATRICKS_DEMO”:

The subscription id can be retrieved using:

Let’s take a closer look at the parameters:

  • name : the desired name of the Service Principal
  • role : the role, which will be assigned. There are different already existing so-called “built-in roles” on Azure . Ensure that a proper role is chosen regarding the purpose of the Service Principal - see List of built-in roles
  • scope : in my example, the Service Principal gets the role “Contributor”, which will be set to the whole subscription. The scope can also be restricted to e.g. a single resource group. Set also the scope carefully - see examples regarding to the value of the scope at learn.microsoft.com - azure-cli-sp-tutorial-1

The Service Principal will be created after executing the command below. The logs will reveal several credentials, save them afterward.

01_create_sp

learn.microsoft.com - azure-cli-sp-tutorial

learn.microsoft.com - az-sp-create-for-rbac

4.3 Get details of the created Service Principal

Specific details of the Service Principal can be listed by using the following command:

Executing that command, lists the DisplayName , the id , the AppId , and the *CreatedDateTime" of all Service Principals , which DisplayName starts with ‘AZ_SP’:

03_list_sp_with_filter

This reveals among others the id , which can be used for an additional command (see below) to retrieve more details.

The green rectangle marks the id of the Service Principal :

04_get_details_of_sp

The access details can also be verified in the Azure Portal , by clicking on the “Check access” button and on the specific Service Principal in the IAM section of the subscription:

02_check_access_of_sp

4.4 Remove permissions from a Service Principal

No worries if you have to reconsider the permissions that you set - they can be updated. Using the following command removes the “Contributor” role for the scope of the whole subscription from the Service Principal named “AZ_SP_AZUREWORKSHOP_PATRICKS_DEMO”:

Checking again the access should prove that there a no current role assignments any more:

05_remove_contributor_of_sp_check

learn.microsoft.com - azure-cli-sp-tutorial-5

learn.microsoft.com - azure-cli-sp-tutorial-1

4.5 Add permissions to a Service Principal

The “Contributor” role was removed, but some proper role assignments would be useful - otherwise, it is not meaningful. Those can be added using the command seen below: in that case, again a “Contributor” role will be assigned, but it is not applied for the whole subscription: the scope is now set to a specific resource group named “githubactions-demonstration” instead:

This restricts the permission of the Service Principal to this resource group:

06_add_contributor_to_rg

Again the access can be verified in the Azure Portal - be aware to prove that at the level of the specific resource group and not at the level for the whole subscription:

06_add_contributor_to_rg_check

Add repository secrets in GitHub

As already mentioned, after creating the Service Principal , the following credentials will appear:

These credentials can be added as repository secrets in GitHub . Three different variables are created:

  • CLIENT_ID - which gets the value of the “appId”
  • CLIENT_SECRET - which gets the value of the “password”
  • TENANT_ID - which gets the value of the “tenant”

Those variables can be used e.g.: in GitHub Actions to establish the connection to the Azure subscription. I’m using that approach now to automate my Azure resources with Terraform and GitHub Actions.

07_add_credentials_to_github

azure.microsoft - Azure subscription

learn.microsoft.com - Azure CLI

learn.microsoft.com - list of built-in roles

learn.microsoft.com - az-ad-sp-list

cloud.hacktricks - az-azuread

stackoverflow.com - how-to-use-filter-with-az-ad-app-to-do-a-bulk-delete

Instantly share code, notes, and snippets.

@garrytrinder

garrytrinder / Add-AppRoleAssignment.ps1

  • Download ZIP
  • Star ( 0 ) 0 You must be signed in to star a gist
  • Fork ( 1 ) 1 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save garrytrinder/6352326eadbc9d00e808022ec724188e to your computer and use it in GitHub Desktop.

Assign Azure Built-In Roles for Access to Resources

You can assign Azure built-in roles to the Azure app registration that you use for Commvault.

  • Prerequisites

If you will use Azure CLI or Azure PowerShell for the steps on this page, use most recent version of the application.

Your Azure account must have the Role Based Access Control Administrator role

  • Azure Portal

In the Azure portal, on the Access Control (IAM) tab, click Add , and then select Add role assignment .

The Add role assignment pane appears.

From the Role list, select the roles that are required for the workload:

From the Assign access to list, select User, group, or service principal .

For Members , do the following:

Click Select members .

The Select members blade appears.

In the Select box, start typing to select the application that you created in the preceding step.

Click Save .

To obtain the tenant ID (which is also the directory ID) from the public Azure cloud, go to Azure Active Directory > Properties > Directory .

To protect Azure resources with your own storage account, repeat the preceding steps to add the Storage Blob Data Contributor role.

Use the following command to assign roles:

az ad sp create-for-rbac -n Azure_app --scopes /subscriptions/${Azure_subscription_ID} --role “role” --output json --only-show-errors Where:

- Azure_app is the name of your Azure app.

- Azure_subscription_ID is the ID of your Azure subscription.

- role is the role to assign.

Required roles for Azure workloads are as follows:

  • Azure PowerShell

Where role is the role to assign.

IMAGES

  1. How to create and test Azure Service Principal using Azure CLI

    azure cli role assignment service principal

  2. How To Create Service Principal In Azure

    azure cli role assignment service principal

  3. Using Service Principal with AzCopy & Azure CLI to manage blobs in

    azure cli role assignment service principal

  4. How To Create Service Principal In Azure

    azure cli role assignment service principal

  5. What is Service Principal?

    azure cli role assignment service principal

  6. Create A Service Principal in Azure using Azure CLI

    azure cli role assignment service principal

VIDEO

  1. Install Azure CLI #azure #azuredevops #azuretips

  2. Cloud Assignment 2

  3. Use Copilot for Azure to Generate Azure CLI Scripts #shorts #copilot

  4. Control Azure Services with Command Line Interface

  5. Azure Managed Identity vs. Service Principal: Choosing the Right Authentication Approach

  6. Terraform vs Azure

COMMENTS

  1. Assign Azure roles using Azure CLI

    Step 1: Determine who needs access. You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111. You can get the ID using the Azure portal or Azure CLI. User.

  2. Assigning Service Principals to Groups and Roles with the Azure CLI

    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. --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.

  3. Create and manage a Service Principal using the Azure CLI

    Let's take a closer look at the parameters: name: the desired name of the Service Principal; role: the role, which will be assigned.There are different already existing so-called "built-in roles" on Azure.Ensure that a proper role is chosen regarding the purpose of the Service Principal - see List of built-in roles; scope: in my example, the Service Principal gets the role "Contributor ...

  4. Creating a Service Principal with the Azure CLI

    Now that we have an AD application, we can create our service principal with az ad sp create-for-rbac (RBAC stands for role based access control). We need to supply an application id and password, so we could create it like this: # choose a password for our service principal. spPassword= "My5erv1c3Pr1ncip@l1!"

  5. What Role or Scopes Does An Azure Service Principal Need to Create

    Also, 'User Access Administrator' role will give the service principal the required permissions for that Azure role to assign RBAC permissions. Please refer the below command for more details: - Please refer the below command for more details: -

  6. Role assignment creation failed through

    This is autogenerated. Please review and update as needed. Describe the bug I'm following the Azure container Apps doc to Create a service principal and store credential. Command Name az ad sp create-for-rbac az ad sp create-for-rbac \ -...

  7. Add AppRole Assignment to Service Principal using Azure CLI

    Add-AppRoleAssignment.ps1. <#. .SYNOPSIS. Assign Application Role to Azure Active Directory service principal. .DESCRIPTION. This script helps assign Application Roles from existing resources to Azure Active Directory service principals, useful for assigning roles to Managed Identity service principals which cannot be performed through the ...

  8. az role assignment list/create fail when listing/creating by Service

    "Cannot find user or service principal in graph database for '{enterprise_application_name}'. If the assignee is an appId, make sure the corresponding service principal is created with 'az ad sp create --id {enterprise_application_name}'." ... Raw command : role assignment list cli.azure.cli.core: Command table: role assignment list cli.knack ...

  9. azure active directory

    The Global admin is an Administrator role in Azure AD, and the Owner is an RBAC role in the subscription. They are different things. When you use the azure cli like below to create the role assignment, it adds the service principal joytestsp as an Owner to the storage account. The service principal which you login needs to call the AAD Graph to ...

  10. From bash unable to create a role assignment for an Service Principal

    I see. I doubt some argument not correctly passed to cli because of the special character. I suggest that you add --debug in the end of the command, then you can see the params received by azure-cli in the first line. For example cli.knack.cli: Command arguments: ['kk', '--debug']

  11. Assign an Azure Custom Role for Least Privilege Access to Resources

    Azure Portal. From the All services menu, click the Subscriptions tab, and then select your subscription ID. On the Access Control (IAM) tab, click Add, and then select Add role assignment. The Add role assignment pane appears. From the Role list, select the custom role. From the Assign access to list, select User, group, or service principal.

  12. Why don't I see Principal Name when I run az role assignment list from

    Why don't I see Principal Name when I run az role assignment list from Azure Devops? I could reproduce this issue with Azure CLI task on my side.. I found there is a similar issue about the Azure cli on the github, so, I am afraid this issue has not been fixed on the azure cli task, it still exists.. To resolve/verify this issue, you could try to use the Azure Powershell task to login and ...

  13. Assign Azure Built-In Roles for Access to Resources

    In the Azure portal, on the Access Control (IAM) tab, click Add, and then select Add role assignment. The Add role assignment pane appears. From the Assign access to list, select User, group, or service principal. Click Select members. The Select members blade appears. In the Select box, start typing to select the application that you created ...

  14. azure

    1.Use Azure portal: Navigate to the vnet in the portal -> Access control (IAM) -> Role assignments -> search for the name of your service principal like below. 2.Use Azure CLI: az role assignment list --assignee SP_CLIENT_ID --scope VNET_ID. answered May 5, 2020 at 5:57.

  15. Unable to query 'principalName' via azure-cli when authenticated as a

    If I perform az login as myself, I'm able to see the following output: (.venv) supertonic09 % az role assignment list --subscription aa11bb33-cc77-dd88-ee99-0918273645aa --role "Owner" --query '[*].principalName' [ "[email protected]", "[email protected]", "[email protected]" ] …but if leverage the --service-principal option, as I'm attempting to develop a check via Python, while I get other ...