Partilhar via


Assign Azure roles using Azure CLI

O controle de acesso baseado em função do Azure (Azure RBAC) é o sistema de autorização que você usa para gerenciar o acesso aos recursos do Azure. Para conceder acesso, atribua funções a usuários, grupos, entidades de serviço ou identidades gerenciadas em um escopo específico. This article describes how to assign roles using Azure CLI.

Pré-requisitos

To assign roles, you must have:

Etapas para atribuir uma função do Azure

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

Etapa 1: Determinar quem precisa de acesso

Você pode atribuir uma função a um usuário, grupo, entidade de serviço ou identidade gerenciada. To assign a role, you might need to specify the unique ID of the object. O ID tem o formato: 11111111-1111-1111-1111-111111111111. You can get the ID using the Azure portal or Azure CLI.

Utilizador

For a Microsoft Entra user, get the user principal name, such as patlong@contoso.com or the user object ID. To get the object ID, you can use az ad user show.

az ad user show --id "{principalName}" --query "id" --output tsv

Grupo

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.

az ad group show --group "{groupName}" --query "id" --output tsv

Serviço 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.

az ad sp list --all --query "[].{displayName:displayName, id:id}" --output tsv
az ad sp list --display-name "{displayName}"

Identidade gerenciada

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.

az ad sp list --all --filter "servicePrincipalType eq 'ManagedIdentity'"

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

az identity list

Etapa 2: Selecione a função apropriada

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.

az role definition list --query "[].{name:name, roleType:roleType, roleName:roleName}" --output tsv

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

az role definition list --name "{roleName}"

For more information, see List Azure role definitions.

Etapa 3: Identificar o escopo necessário

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. Para obter mais informações sobre escopo, consulte Entender escopo.

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.

/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceSubType}/{resourceName}

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.

az group list --query "[].{name:name}" --output tsv

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.

az account list --query "[].{name:name, id:id}" --output tsv

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.

az account management-group list --query "[].{name:name, id:id}" --output tsv

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.

Resource scope

az role assignment create --assignee "{assignee}" \
--role "{roleNameOrId}" \
--scope "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceSubType}/{resourceName}"

Resource group scope

az role assignment create --assignee "{assignee}" \
--role "{roleNameOrId}" \
--scope "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}"

Subscription scope

az role assignment create --assignee "{assignee}" \
--role "{roleNameOrId}" \
--scope "/subscriptions/{subscriptionId}"

Management group scope

az role assignment create --assignee "{assignee}" \
--role "{roleNameOrId}" \
--scope "/providers/Microsoft.Management/managementGroups/{managementGroupName}"

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

{
  "canDelegate": null,
  "id": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}",
  "name": "{roleAssignmentId}",
  "principalId": "{principalId}",
  "principalType": "User",
  "resourceGroup": "{resourceGroupName}",
  "roleDefinitionId": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/9980e02c-c2be-4d73-94e8-173b1dc7cf3c",
  "scope": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}",
  "type": "Microsoft.Authorization/roleAssignments"
}

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.

az role assignment create --assignee "55555555-5555-5555-5555-555555555555" \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Example-Storage-rg/providers/Microsoft.Storage/storageAccounts/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.

az role assignment create --assignee "55555555-5555-5555-5555-555555555555" \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Example-Storage-rg/providers/Microsoft.Storage/storageAccounts/storage12345/blobServices/default/containers/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.

az role assignment create --assignee "22222222-2222-2222-2222-222222222222" \
--role "Virtual Machine Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/pharma-sales/providers/Microsoft.Network/virtualNetworks/pharma-sales-project-network"

Assign a role for a user at a resource group scope

Assigns the Virtual Machine Contributor role to patlong@contoso.com user at the pharma-sales resource group scope.

az role assignment create --assignee "patlong@contoso.com" \
--role "Virtual Machine Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/pharma-sales"

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.

Mesmo que uma função seja renomeada, a ID da função não é alterada. Se você estiver usando scripts ou automação para criar suas atribuições de função, é uma prática recomendada usar o ID de função exclusivo em vez do nome da função. Portanto, se uma função for renomeada, é mais provável que seus scripts funcionem.

The following example assigns the Virtual Machine Contributor role to the patlong@contoso.com user at the pharma-sales resource group scope.

az role assignment create --assignee "patlong@contoso.com" \
--role "9980e02c-c2be-4d73-94e8-173b1dc7cf3c" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/pharma-sales"

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.

az role assignment create --assignee "55555555-5555-5555-5555-555555555555" \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/Example-Storage-rg"

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.

az role assignment create --assignee "44444444-4444-4444-4444-444444444444" \
--role "Virtual Machine Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/pharma-sales"

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

Se você criar uma nova entidade de serviço e tentar atribuir imediatamente uma função a essa entidade de serviço, essa atribuição de função poderá falhar em alguns casos. 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. A razão para essa falha é provavelmente um atraso na replicação. A entidade de serviço é criada em uma região; no entanto, a atribuição de função pode ocorrer em uma região diferente que ainda não replicou a entidade de serviço. 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.

az role assignment create --assignee-object-id "{assigneeObjectId}" \
--assignee-principal-type "{assigneePrincipalType}" \
--role "{roleNameOrId}" \
--scope "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}"

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

az role assignment create --assignee-object-id "33333333-3333-3333-3333-333333333333" \
--assignee-principal-type "ServicePrincipal" \
--role "Virtual Machine Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/pharma-sales"

Assign a role for a user at a subscription scope

Assigns the Reader role to the annm@example.com user at a subscription scope.

az role assignment create --assignee "annm@example.com" \
--role "Reader" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000"

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.

az role assignment create --assignee "22222222-2222-2222-2222-222222222222" \
--role "Reader" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000"

Assign a role for all blob containers at a subscription scope

Assigns the Storage Blob Data Reader role to the alain@example.com user at a subscription scope.

az role assignment create --assignee "alain@example.com" \
--role "Storage Blob Data Reader" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000"

Assign a role for a user at a management group scope

Assigns the Billing Reader role to the alain@example.com user at a management group scope.

az role assignment create --assignee "alain@example.com" \
--role "Billing Reader" \
--scope "/providers/Microsoft.Management/managementGroups/marketing-group"

Próximos passos