使用 Azure 资源管理器模板添加 Azure 角色分配Add Azure role assignments using Azure Resource Manager templates

Azure 基于角色的访问控制 (RBAC) 是用于管理对 Azure 资源的访问权限的授权系统。Azure role-based access control (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. 除了使用 Azure PowerShell 或 Azure CLI 之外,还可以使用 Azure 资源管理器模板分配角色。Azure 基于角色的访问控制 (RBAC) 是用于管理对 Azure 资源的访问权限的授权系统。Azure role-based access control (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. In addition to using Azure PowerShell or the Azure CLI, you can assign roles using Azure Resource Manager templates. 如果需要一致且重复地部署资源,模板会很有用。Templates can be helpful if you need to deploy resources consistently and repeatedly. 本文介绍如何使用模板分配角色。This article describes how to assign roles using templates.

获取对象 IDGet object IDs

若要分配角色,需要指定要为其分配角色的用户、组或应用程序的 ID。To assign a role, you need to specify the ID of the user, group, or application you want to assign the role to. ID 的格式为:11111111-1111-1111-1111-111111111111The ID has the format: 11111111-1111-1111-1111-111111111111. 可以使用 Azure 门户、Azure PowerShell 或 Azure CLI 来获取 ID。You can get the ID using the Azure portal, Azure PowerShell, or Azure CLI.

用户User

若要获取用户的 ID,可以使用 Get-AzADUseraz ad user show 命令。To get the ID of a user, you can use the Get-AzADUser or az ad user show commands.

$objectid = (Get-AzADUser -DisplayName "{name}").id
objectid=$(az ad user show --id "{email}" --query objectId --output tsv)

Group

若要获取组的 ID,可以使用 Get-AzADGroupaz ad group show 命令。To get the ID of a group, you can use the Get-AzADGroup or az ad group show commands.

$objectid = (Get-AzADGroup -DisplayName "{name}").id
objectid=$(az ad group show --group "{name}" --query objectId --output tsv)

应用程序Application

若要获取服务主体(应用程序使用的标识)的 ID,可以使用 Get-AzADServicePrincipalaz ad sp list 命令。To get the ID of a service principal (identity used by an application), you can use the Get-AzADServicePrincipal or az ad sp list commands. 对于服务主体,使用对象 ID,而不是应用程序 ID。For a service principal, use the object ID and not the application ID.

$objectid = (Get-AzADServicePrincipal -DisplayName "{name}").id
objectid=$(az ad sp list --display-name "{name}" --query [].objectId --output tsv)

添加角色分配Add a role assignment

在 Azure RBAC 中,若要授予访问权限,请添加角色分配。In Azure RBAC, to grant access, you add a role assignment.

资源组(不包含参数)Resource group (without parameters)

以下模板演示了添加角色分配的基本方法。The following template shows a basic way to add a role assignment. 某些值在模板中指定。Some values are specified within the template. 以下模板演示:The following template demonstrates:

  • 如何将读者角色分配给资源组范围内的用户、组或应用程序How to assign the Reader role to a user, group, or application at a resource group scope

若要使用模板,必须执行以下操作:To use the template, you must do the following:

  • 创建新的 JSON 文件并复制模板Create a new JSON file and copy the template
  • <your-principal-id> 替换为要为其分配角色的用户、组或应用程序Replace <your-principal-id> with the ID of a user, group, or application to assign the role to
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        {
            "type": "Microsoft.Authorization/roleAssignments",
            "apiVersion": "2018-09-01-preview",
            "name": "[guid(resourceGroup().id)]",
            "properties": {
                "roleDefinitionId": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]",
                "principalId": "<your-principal-id>"
            }
        }
    ]
}

下面是演示如何在名为 ExampleGroup 的资源组中启动部署的示例 New-AzResourceGroupDeploymentaz group deployment create 命令。Here are example New-AzResourceGroupDeployment and az group deployment create commands for how to start the deployment in a resource group named ExampleGroup.

New-AzResourceGroupDeployment -ResourceGroupName ExampleGroup -TemplateFile rbac-test.json
az group deployment create --resource-group ExampleGroup --template-file rbac-test.json

下面显示了在部署模板后向资源组的用户分配“读者”角色的示例。The following shows an example of the Reader role assignment to a user for a resource group after deploying the template.

资源组范围内的角色分配

资源组或订阅Resource group or subscription

上一个模板不太灵活。The previous template isn't very flexible. 以下模板使用参数,并且可以在不同的范围内使用。The following template uses parameters and can be used at different scopes. 以下模板演示:The following template demonstrates:

  • 如何将角色分配给资源组范围或订阅范围内的用户、组或应用程序How to assign a role to a user, group, or application at either a resource group or subscription scope
  • 如何将“所有者”、“参与者”和“读者”角色指定为参数How to specify the Owner, Contributor, and Reader roles as a parameter

若要使用模板,必须指定以下输入:To use the template, you must specify the following inputs:

  • 要为其分配角色的用户、组或应用程序 IDThe ID of a user, group, or application to assign the role to
  • 将用于角色分配的唯一 ID,或者可以使用默认 IDA unique ID that will be used for the role assignment, or you can use the default ID
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "principalId": {
            "type": "string",
            "metadata": {
                "description": "The principal to assign the role to"
            }
        },
        "builtInRoleType": {
            "type": "string",
            "allowedValues": [
                "Owner",
                "Contributor",
                "Reader"
            ],
            "metadata": {
                "description": "Built-in role to assign"
            }
        },
        "roleNameGuid": {
            "type": "string",
            "defaultValue": "[newGuid()]",
            "metadata": {
                "description": "A new GUID used to identify the role assignment"
            }
        }
    },
    "variables": {
        "Owner": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')]",
        "Contributor": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
        "Reader": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]"
    },
    "resources": [
        {
            "type": "Microsoft.Authorization/roleAssignments",
            "apiVersion": "2018-09-01-preview",
            "name": "[parameters('roleNameGuid')]",
            "properties": {
                "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
                "principalId": "[parameters('principalId')]"
            }
        }
    ]
}

备注

此模板不是幂等的,除非将同一 roleNameGuid 值作为模板的每个部署的参数提供。This template is not idempotent unless the same roleNameGuid value is provided as a parameter for each deployment of the template. 如果未提供 roleNameGuid,则默认情况下将在每个部署上生成新的 GUID,并且后续部署将失败并出现 Conflict: RoleAssignmentExists 错误。If no roleNameGuid is provided, by default a new GUID is generated on each deployment and subsequent deployments will fail with a Conflict: RoleAssignmentExists error.

角色分配的范围是根据部署级别确定的。The scope of the role assignment is determined from the level of the deployment. 下面是演示如何在资源组范围内启动部署的示例 New-AzResourceGroupDeploymentaz group deployment create 命令。Here are example New-AzResourceGroupDeployment and az group deployment create commands for how to start the deployment at a resource group scope.

New-AzResourceGroupDeployment -ResourceGroupName ExampleGroup -TemplateFile rbac-test.json -principalId $objectid -builtInRoleType Reader
az group deployment create --resource-group ExampleGroup --template-file rbac-test.json --parameters principalId=$objectid builtInRoleType=Reader

下面是演示如何在订阅范围内启动部署并指定位置的示例 New-AzDeploymentaz deployment create 命令。Here are example New-AzDeployment and az deployment create commands for how to start the deployment at a subscription scope and specify the location.

New-AzDeployment -Location chinanorth -TemplateFile rbac-test.json -principalId $objectid -builtInRoleType Reader
az deployment create --location chinanorth --template-file rbac-test.json --parameters principalId=$objectid builtInRoleType=Reader

资源Resource

如果需要在资源级别添加角色分配,则角色分配的格式是不同的。If you need to add a role assignment at the level of a resource, the format of the role assignment is different. 提供要为其分配角色的资源的资源提供程序命名空间和资源类型。You provide the resource provider namespace and resource type of the resource to assign the role to. 还在角色分配的名称中包含资源的名称。You also include the name of the resource in the name of the role assignment.

对于角色分配的类型和名称,使用以下格式:For the type and name of the role assignment, use the following format:

"type": "{resource-provider-namespace}/{resource-type}/providers/roleAssignments",
"name": "{resource-name}/Microsoft.Authorization/{role-assign-GUID}"

以下模板演示:The following template demonstrates:

  • 如何新建存储帐户How to create a new storage account
  • 如何将角色分配给存储帐户范围内的用户、组或应用程序How to assign a role to a user, group, or application at the storage account scope
  • 如何将“所有者”、“参与者”和“读者”角色指定为参数How to specify the Owner, Contributor, and Reader roles as a parameter

若要使用模板,必须指定以下输入:To use the template, you must specify the following inputs:

  • 要为其分配角色的用户、组或应用程序 IDThe ID of a user, group, or application to assign the role to
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "principalId": {
            "type": "string",
            "metadata": {
                "description": "The principal to assign the role to"
            }
        },
        "builtInRoleType": {
            "type": "string",
            "allowedValues": [
                "Owner",
                "Contributor",
                "Reader"
            ],
            "metadata": {
                "description": "Built-in role to assign"
            }
        },
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]"
        }
    },
    "variables": {
        "Owner": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')]",
        "Contributor": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
        "Reader": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')]",
        "storageName": "[concat('storage', uniqueString(resourceGroup().id))]"
    },
    "resources": [
        {
            "apiVersion": "2019-04-01",
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[variables('storageName')]",
            "location": "[parameters('location')]",
            "sku": {
                "name": "Standard_LRS"
            },
            "kind": "Storage",
            "properties": {}
        },
        {
            "type": "Microsoft.Storage/storageAccounts/providers/roleAssignments",
            "apiVersion": "2018-09-01-preview",
            "name": "[concat(variables('storageName'), '/Microsoft.Authorization/', guid(uniqueString(variables('storageName'))))]",
            "dependsOn": [
                "[variables('storageName')]"
            ],
            "properties": {
                "roleDefinitionId": "[variables(parameters('builtInRoleType'))]",
                "principalId": "[parameters('principalId')]"
            }
        }
    ]
}

若要部署上一个模板,请使用资源组命令。To deploy the previous template, you use the resource group commands. 下面是演示如何在资源范围内启动部署的示例 New-AzResourceGroupDeploymentaz group deployment create 命令。Here are example New-AzResourceGroupDeployment and az group deployment create commands for how to start the deployment at a resource scope.

New-AzResourceGroupDeployment -ResourceGroupName ExampleGroup -TemplateFile rbac-test.json -principalId $objectid -builtInRoleType Contributor
az group deployment create --resource-group ExampleGroup --template-file rbac-test.json --parameters principalId=$objectid builtInRoleType=Contributor

下面显示了在部署模板后向存储帐户的用户分配“参与者”角色的示例。The following shows an example of the Contributor role assignment to a user for a storage account after deploying the template.

资源范围内的角色分配

新服务主体New service principal

如果创建新服务主体并立即尝试将角色分配给该服务主体,则在某些情况下该角色分配可能会失败。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. 例如,如果创建新托管标识,然后尝试将角色分配给同一 Azure 资源管理器模板中的服务主体,则角色分配可能会失败。For example, if you create a new managed identity and then try to assign a role to that service principal in the same Azure Resource Manager template, 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. 若要解决这种情况,应在创建角色分配时将 principalType 属性设置为 ServicePrincipalTo address this scenario, you should set the principalType property to ServicePrincipal when creating the role assignment.

以下模板演示:The following template demonstrates:

  • 如何创建新的托管标识服务主体How to create a new managed identity service principal
  • 如何指定 principalTypeHow to specify the principalType
  • 如何将“参与者”角色分配给资源组范围内的服务主体How to assign the Contributor role to that service principal at a resource group scope

若要使用模板,必须指定以下输入:To use the template, you must specify the following inputs:

  • 托管标识的基名称,或者可以使用默认字符串The base name of the managed identity, or you can use the default string
{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "baseName": {
            "type": "string",
            "defaultValue": "msi-test"
        }
    },
    "variables": {
        "identityName": "[concat(parameters('baseName'), '-bootstrap')]",
        "bootstrapRoleAssignmentId": "[guid(concat(resourceGroup().id, 'contributor'))]",
        "contributorRoleDefinitionId": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]"
    },
    "resources": [
        {
            "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
            "name": "[variables('identityName')]",
            "apiVersion": "2018-11-30",
            "location": "[resourceGroup().location]"
        },
        {
            "type": "Microsoft.Authorization/roleAssignments",
            "apiVersion": "2018-09-01-preview",
            "name": "[variables('bootstrapRoleAssignmentId')]",
            "dependsOn": [
                "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]"
            ],
            "properties": {
                "roleDefinitionId": "[variables('contributorRoleDefinitionId')]",
                "principalId": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName')), '2018-11-30').principalId]",
                "scope": "[resourceGroup().id]",
                "principalType": "ServicePrincipal"
            }
        }
    ]
}

下面是演示如何在资源组范围内启动部署的示例 New-AzResourceGroupDeploymentaz group deployment create 命令。Here are example New-AzResourceGroupDeployment and az group deployment create commands for how to start the deployment at a resource group scope.

New-AzResourceGroupDeployment -ResourceGroupName ExampleGroup2 -TemplateFile rbac-test.json
az group deployment create --resource-group ExampleGroup2 --template-file rbac-test.json

下面显示了在部署模板后向新的托管标识服务主体分配“参与者”角色的示例。The following shows an example of the Contributor role assignment to a new managed identity service principal after deploying the template.

新的托管标识服务主体的角色分配

删除角色分配Remove a role assignment

在 Azure RBAC 中,若要删除对 Azure 资源的访问权限,则删除该角色分配。In Azure RBAC, to remove access to an Azure resource, you remove the role assignment. 无法使用模板删除角色分配。There isn't a way to remove a role assignment using a template. 若要删除角色分配,必须使用其他工具,例如:To remove a role assignment, you must use other tools such as:

后续步骤Next steps