使用 ARM 模板创建或更新 Azure 自定义角色Create or update Azure custom roles using an ARM template

如果 Azure 内置角色不满足组织的特定需求,你可以创建自己的自定义角色If the Azure built-in roles don't meet the specific needs of your organization, you can create your own custom roles. 本文介绍如何使用 Azure 资源管理器模板(ARM 模板)来创建或更新自定义角色。This article describes how to create or update a custom role using an Azure Resource Manager template (ARM template).

ARM 模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. 该模板使用声明性语法,使你可以声明要部署的内容,而不需要编写一系列编程命令来进行创建。The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it.

若要创建自定义角色,请指定角色名称、权限以及可使用角色的位置。To create a custom role, you specify a role name, permissions, and where the role can be used. 在本文中,你将创建一个名为“自定义角色 - RG 读者”的角色,其资源权限可在订阅或更低层次的范围内分配。In this article, you create a role named Custom Role - RG Reader with resource permissions that can be assigned at a subscription scope or lower.

如果你的环境满足先决条件,并且你熟悉如何使用 ARM 模板,请选择“部署到 Azure”按钮。If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. Azure 门户中会打开模板。The template will open in the Azure portal.

部署到 AzureDeploy to Azure

先决条件Prerequisites

若要创建自定义角色,必须:To create a custom role, you must have:

查看模板Review the template

本文中使用的模板来自 Azure 快速入门模板The template used in this article is from Azure Quickstart Templates. 该模板具有四个参数和一个资源部分。The template has four parameters and a resources section. 这四个参数为:The four parameters are:

  • 默认值为 ["Microsoft.Resources/subscriptions/resourceGroups/read"] 的操作数组。Array of actions with a default value of ["Microsoft.Resources/subscriptions/resourceGroups/read"].
  • 默认值为空的 notActions 数组。Array of notActions with an empty default value.
  • 默认值为 Custom Role - RG Reader 的角色名称。Role name with a default value of Custom Role - RG Reader.
  • 默认值为 Subscription Level Deployment of a Role Definition 的角色说明。Role description with a default value of Subscription Level Deployment of a Role Definition.

将可分配此自定义角色的范围设置为当前订阅。The scope where this custom role can be assigned is set to the current subscription.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "actions": {
      "type": "array",
      "defaultValue": [
        "Microsoft.Resources/subscriptions/resourceGroups/read"
      ],
      "metadata": {
        "description": "Array of actions for the roleDefinition"
      }
    },
    "notActions": {
      "type": "array",
      "defaultValue": [],
      "metadata": {
        "description": "Array of notActions for the roleDefinition"
      }
    },
    "roleName": {
      "type": "string",
      "defaultValue": "Custom Role - RG Reader",
      "metadata": {
        "description": "Friendly name of the role definition"
      }
    },
    "roleDescription": {
      "type": "string",
      "defaultValue": "Subscription Level Deployment of a Role Definition",
      "metadata": {
        "description": "Detailed description of the role definition"
      }
    }
  },
  "variables": {
    "roleDefName": "[guid(subscription().id, string(parameters('actions')), string(parameters('notActions')))]"
  },
  "resources": [
    {
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2018-07-01",
      "name": "[variables('roleDefName')]",
      "properties": {
        "roleName": "[parameters('roleName')]",
        "description": "[parameters('roleDescription')]",
        "type": "customRole",
        "isCustom": true,
        "permissions": [
          {
            "actions": "[parameters('actions')]",
            "notActions": "[parameters('notActions')]"
          }
        ],
        "assignableScopes": [
          "[subscription().id]"
        ]
      }
    }
  ]
}

该模板中定义了以下资源:The resource defined in the template is:

部署模板Deploy the template

请遵照以下步骤部署上一模板。Follow these steps to deploy the previous template.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 打开 PowerShell。Open PowerShell. 登录到你的订阅,然后复制并粘贴以下脚本。Login with your subscription then copy and paste the following script.

    $location = Read-Host -Prompt "Enter a location (i.e. chinanorth)"
    [string[]]$actions = Read-Host -Prompt "Enter actions as a comma-separated list (i.e. action1,action2)"
    $actions = $actions.Split(',')
    $templateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/subscription-deployments/create-role-def/azuredeploy.json"
    New-AzDeployment -Location $location -TemplateUri $templateUri -actions $actions
    
  3. 输入部署的位置,例如 chinanorth。Enter a location for the deployment such as chinanorth.

  4. 以逗号分隔的列表(如 Microsoft.Resources/resources/read,Microsoft.Resources/subscriptions/resourceGroups/read)形式输入自定义角色的操作列表。Enter a list of actions for the custom role as a comma-separated list such as Microsoft.Resources/resources/read,Microsoft.Resources/subscriptions/resourceGroups/read.

  5. 如有必要,请按 Enter 运行 New-AzDeployment 命令。If necessary, press Enter to run the New-AzDeployment command.

    New-AzDeployment 命令部署模板来创建自定义角色。The New-AzDeployment command deploys the template to create the custom role.

    会得到类似于下面的输出:You should see output similar to the following:

    PS> New-AzDeployment -Location $location -TemplateUri $templateUri -actions $actions
    
    Id                      : /subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/azuredeploy
    DeploymentName          : azuredeploy
    Location                : chinanorth
    ProvisioningState       : Succeeded
    Timestamp               : 6/25/2020 8:08:32 PM
    Mode                    : Incremental
    TemplateLink            :
                              Uri            : https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/subscription-deployments/create-role-def/azuredeploy.json
                              ContentVersion : 1.0.0.0
    
    Parameters              :
                              Name               Type                       Value
                              =================  =========================  ==========
                              actions            Array                      [
                                "Microsoft.Resources/resources/read",
                                "Microsoft.Resources/subscriptions/resourceGroups/read"
                              ]
                              notActions         Array                      []
                              roleName           String                     Custom Role - RG Reader
                              roleDescription    String                     Subscription Level Deployment of a Role Definition
    
    Outputs                 :
    DeploymentDebugLogLevel :
    

查看已部署的资源Review deployed resources

按照以下步骤验证是否已创建自定义角色。Follow these steps to verify that the custom role was created.

  1. 运行 Get-AzRoleDefinition 命令以列出自定义角色。Run the Get-AzRoleDefinition command to list the custom role.

    Get-AzRoleDefinition "Custom Role - RG Reader" | ConvertTo-Json
    

    应该会看到与下面类似的输出:You should see output similar to the following:

    {
      "Name": "Custom Role - RG Reader",
      "Id": "11111111-1111-1111-1111-111111111111",
      "IsCustom": true,
      "Description": "Subscription Level Deployment of a Role Definition",
      "Actions": [
        "Microsoft.Resources/resources/read",
        "Microsoft.Resources/subscriptions/resourceGroups/read"
      ],
      "NotActions": [],
      "DataActions": [],
      "NotDataActions": [],
      "AssignableScopes": [
        "/subscriptions/{subscriptionId}"
      ]
    }
    
  2. 在 Azure 门户中,打开你的订阅。In the Azure portal, open your subscription.

  3. 在左侧菜单中,选择“访问控制(IAM)”。In the left menu, select Access control (IAM).

  4. 选择“角色”选项卡。Select the Roles tab.

  5. 将“类型”列表设置为 CustomRole 。Set the Type list to CustomRole.

  6. 验证是否列出了“自定义角色 - RG 读者”角色。Verify that the Custom Role - RG Reader role is listed.

    在 Azure 门户中新建自定义角色

更新自定义角色Update a custom role

与创建自定义角色类似,可以通过使用模板来更新现有的自定义角色。Similar to creating a custom role, you can update an existing custom role by using a template. 若要更新自定义角色,必须指定需要更新的角色。To update a custom role, you must specify the role you want to update.

下面是为了更新自定义角色而需要对上一个快速入门模板做出的更改。Here are the changes you would need to make to the previous Quickstart template to update the custom role.

  • 将角色 ID 作为参数包括在内。Include the role ID as a parameter.

        ...
        "roleDefName": {
          "type": "string",
          "metadata": {
            "description": "ID of the role definition"
          }
        ...
    
  • 在角色定义中包括角色 ID 参数。Include the role ID parameter in the role definition.

      ...
      "resources": [
        {
          "type": "Microsoft.Authorization/roleDefinitions",
          "apiVersion": "2018-07-01",
          "name": "[parameters('roleDefName')]",
          "properties": {
            ...
    

以下示例演示如何部署该模板。Here's an example of how to deploy the template.

$location = Read-Host -Prompt "Enter a location (i.e. chinanorth)"
[string[]]$actions = Read-Host -Prompt "Enter actions as a comma-separated list (i.e. action1,action2)"
$actions = $actions.Split(',')
$roleDefName = Read-Host -Prompt "Enter the role ID to update"
$templateFile = "rg-reader-update.json"
New-AzDeployment -Location $location -TemplateFile $templateFile -actions $actions -roleDefName $roleDefName

清理资源Clean up resources

若要删除自定义角色,请按照以下步骤操作。To remove the custom role, follow these steps.

  1. 运行以下命令以删除自定义角色。Run the following command to remove the custom role.

    Get-AzRoleDefinition -Name "Custom Role - RG Reader" | Remove-AzRoleDefinition
    
  2. 输入“Y”以确认要删除该自定义角色。Enter Y to confirm that you want to remove the custom role.

后续步骤Next steps