使用 Azure PowerShell 创建或更新 Azure 自定义角色Create or update Azure custom roles using Azure PowerShell

Important

将管理组添加到 AssignableScopes 的功能目前为预览版。Adding a management group to AssignableScopes is currently in preview. 此预览版在提供时没有附带服务级别协议,不建议将其用于生产工作负荷。This preview version is provided without a service level agreement, and it's not recommended for production workloads. 某些功能可能不受支持或者受限。Certain features might not be supported or might have constrained capabilities. 有关详细信息,请参阅适用于 Azure 预览版的补充使用条款For more information, see Supplemental Terms of Use for Azure Previews.

如果 Azure 内置角色不满足组织的特定需求,你可以创建自己的自定义角色。If the Azure built-in roles don't meet the specific needs of your organization, you can create your own custom roles. 本文介绍如何使用 Azure PowerShell 列出、创建、更新或删除自定义角色。This article describes how to list, create, update, or delete custom roles using Azure PowerShell.

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

先决条件Prerequisites

若要创建自定义角色,需要具备以下条件:To create custom roles, you need:

列出自定义角色List custom roles

若要列出可在某范围内进行分配的角色,请使用 Get-AzRoleDefinition 命令。To list the roles that are available for assignment at a scope, use the Get-AzRoleDefinition command. 以下示例列出了可在所选订阅中进行分配的所有角色。The following example lists all roles that are available for assignment in the selected subscription.

Get-AzRoleDefinition | FT Name, IsCustom
Name                                              IsCustom
----                                              --------
Virtual Machine Operator                              True
AcrImageSigner                                       False
AcrQuarantineReader                                  False
AcrQuarantineWriter                                  False
API Management Service Contributor                   False
...

以下示例仅列出了可在所选订阅中进行分配的自定义角色。The following example lists just the custom roles that are available for assignment in the selected subscription.

Get-AzRoleDefinition | ? {$_.IsCustom -eq $true} | FT Name, IsCustom
Name                     IsCustom
----                     --------
Virtual Machine Operator     True

如果所选订阅不在角色的 AssignableScopes 中,则不会列出自定义角色。If the selected subscription isn't in the AssignableScopes of the role, the custom role won't be listed.

列出自定义角色定义List a custom role definition

若要列出自定义角色定义,请使用 Get-AzRoleDefinitionTo list a custom role definition, use Get-AzRoleDefinition. 这与用于内置角色的命令相同。This is the same command as you use for a built-in role.

Get-AzRoleDefinition <role_name> | ConvertTo-Json
PS C:\> Get-AzRoleDefinition "Virtual Machine Operator" | ConvertTo-Json

{
  "Name": "Virtual Machine Operator",
  "Id": "00000000-0000-0000-0000-000000000000",
  "IsCustom": true,
  "Description": "Can monitor and restart virtual machines.",
  "Actions": [
    "Microsoft.Storage/*/read",
    "Microsoft.Network/*/read",
    "Microsoft.Compute/*/read",
    "Microsoft.Compute/virtualMachines/start/action",
    "Microsoft.Compute/virtualMachines/restart/action",
    "Microsoft.Authorization/*/read",
    "Microsoft.ResourceHealth/availabilityStatuses/read",
    "Microsoft.Resources/subscriptions/resourceGroups/read",
    "Microsoft.Insights/alertRules/*"
  ],
  "NotActions": [],
  "DataActions": [],
  "NotDataActions": [],
  "AssignableScopes": [
    "/subscriptions/11111111-1111-1111-1111-111111111111"
  ]
}

以下示例仅列出了角色的操作:The following example lists just the actions of the role:

(Get-AzRoleDefinition <role_name>).Actions
PS C:\> (Get-AzRoleDefinition "Virtual Machine Operator").Actions

"Microsoft.Storage/*/read",
"Microsoft.Network/*/read",
"Microsoft.Compute/*/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Authorization/*/read",
"Microsoft.ResourceHealth/availabilityStatuses/read",
"Microsoft.Resources/subscriptions/resourceGroups/read",
"Microsoft.Insights/alertRules/*",
"Microsoft.Insights/diagnosticSettings/*"

创建自定义角色Create a custom role

若要创建自定义角色,请使用 New-AzRoleDefinition 命令。To create a custom role, use the New-AzRoleDefinition command. 构造角色有两种方法:使用 PSRoleDefinition 对象或 JSON 模板。There are two methods of structuring the role, using PSRoleDefinition object or a JSON template.

获取资源提供程序的操作Get operations for a resource provider

创建自定义角色时,请务必了解资源提供程序的所有可能操作。When you create custom roles, it is important to know all the possible operations from the resource providers. 可以查看资源提供程序操作的列表,也可以使用 Get-AzProviderOperation 命令获取该信息。You can view the list of resource provider operations or you can use the Get-AzProviderOperation command to get this information. 例如,如果想要查看虚拟机的所有可用操作,请使用此命令:For example, if you want to check all the available operations for virtual machines, use this command:

Get-AzProviderOperation <operation> | FT OperationName, Operation, Description -AutoSize
PS C:\> Get-AzProviderOperation "Microsoft.Compute/virtualMachines/*" | FT OperationName, Operation, Description -AutoSize

OperationName                                  Operation                                                      Description
-------------                                  ---------                                                      -----------
Get Virtual Machine                            Microsoft.Compute/virtualMachines/read                         Get the propertie...
Create or Update Virtual Machine               Microsoft.Compute/virtualMachines/write                        Creates a new vir...
Delete Virtual Machine                         Microsoft.Compute/virtualMachines/delete                       Deletes the virtu...
Start Virtual Machine                          Microsoft.Compute/virtualMachines/start/action                 Starts the virtua...
...

使用 PSRoleDefinition 对象创建自定义角色Create a custom role with the PSRoleDefinition object

使用 PowerShell 创建自定义角色时,可以使用某个内置角色作为起点,也可以从头开始。When you use PowerShell to create a custom role, you can use one of the built-in roles as a starting point or you can start from scratch. 本部分中的第一个示例以内置角色开始,并为它自定义更多的权限。The first example in this section starts with a built-in role and then customizes it with more permissions. 编辑属性以添加所需的 ActionsNotActionsAssignableScopes,然后将这些更改保存为新角色。Edit the attributes to add the Actions, NotActions, or AssignableScopes that you want, and then save the changes as a new role.

以下示例从虚拟机参与者内置角色开始,使用该角色创建名为“虚拟机操作员”的自定义角色。The following example starts with the Virtual Machine Contributor built-in role to create a custom role named Virtual Machine Operator. 该新角色授权访问 Microsoft.Compute、Microsoft.Storage 和 Microsoft.Network 资源提供程序的所有读取操作,并授权访问启动、重新启动和监视操作 。The new role grants access to all read operations of Microsoft.Compute, Microsoft.Storage, and Microsoft.Network resource providers and grants access to start, restart, and monitor virtual machines. 该自定义角色可以在两个订阅中使用。The custom role can be used in two subscriptions.

$role = Get-AzRoleDefinition "Virtual Machine Contributor"
$role.Id = $null
$role.Name = "Virtual Machine Operator"
$role.Description = "Can monitor and restart virtual machines."
$role.Actions.Clear()
$role.Actions.Add("Microsoft.Storage/*/read")
$role.Actions.Add("Microsoft.Network/*/read")
$role.Actions.Add("Microsoft.Compute/*/read")
$role.Actions.Add("Microsoft.Compute/virtualMachines/start/action")
$role.Actions.Add("Microsoft.Compute/virtualMachines/restart/action")
$role.Actions.Add("Microsoft.Authorization/*/read")
$role.Actions.Add("Microsoft.ResourceHealth/availabilityStatuses/read")
$role.Actions.Add("Microsoft.Resources/subscriptions/resourceGroups/read")
$role.Actions.Add("Microsoft.Insights/alertRules/*")
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add("/subscriptions/00000000-0000-0000-0000-000000000000")
$role.AssignableScopes.Add("/subscriptions/11111111-1111-1111-1111-111111111111")
New-AzRoleDefinition -Role $role

以下示例显示创建“虚拟机操作员”自定义角色的另一种方式。The following example shows another way to create the Virtual Machine Operator custom role. 首先,创建一个新 PSRoleDefinition 对象。It starts by creating a new PSRoleDefinition object. perms 变量中指定操作,然后将操作设置为 Actions 属性。The action operations are specified in the perms variable and set to the Actions property. 通过从 虚拟机参与者内置角色读取 NotActions 设置 NotActions 属性。The NotActions property is set by reading the NotActions from the Virtual Machine Contributor built-in role. 由于虚拟机参与者没有任何 NotActions,因此不需要此行,但它显示了从另一个角色检索信息的方式。Since Virtual Machine Contributor does not have any NotActions, this line is not required, but it shows how information can be retrieved from another role.

$role = [Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition]::new()
$role.Name = 'Virtual Machine Operator 2'
$role.Description = 'Can monitor and restart virtual machines.'
$role.IsCustom = $true
$perms = 'Microsoft.Storage/*/read','Microsoft.Network/*/read','Microsoft.Compute/*/read'
$perms += 'Microsoft.Compute/virtualMachines/start/action','Microsoft.Compute/virtualMachines/restart/action'
$perms += 'Microsoft.Authorization/*/read'
$perms += 'Microsoft.ResourceHealth/availabilityStatuses/read'
$perms += 'Microsoft.Resources/subscriptions/resourceGroups/read'
$role.Actions = $perms
$role.NotActions = (Get-AzRoleDefinition -Name 'Virtual Machine Contributor').NotActions
$subs = '/subscriptions/00000000-0000-0000-0000-000000000000','/subscriptions/11111111-1111-1111-1111-111111111111'
$role.AssignableScopes = $subs
New-AzRoleDefinition -Role $role

使用 JSON 模板创建自定义角色Create a custom role with JSON template

JSON 模板可以用作自定义角色的源定义。A JSON template can be used as the source definition for the custom role. 以下示例创建一个可以对存储和计算资源进行读取访问以及获取支持的自定义角色,并将该角色添加到两个订阅。The following example creates a custom role that allows read access to storage and compute resources, access to support, and adds that role to two subscriptions. 创建包含以下示例的新文件 C:\CustomRoles\customrole1.jsonCreate a new file C:\CustomRoles\customrole1.json with the following example. 创建初始角色时,应将 ID 设置为 null,因为会自动生成新的 ID。The Id should be set to null on initial role creation as a new ID is generated automatically.

{
  "Name": "Custom Role 1",
  "Id": null,
  "IsCustom": true,
  "Description": "Allows for read access to Azure storage and compute resources and access to support",
  "Actions": [
    "Microsoft.Compute/*/read",
    "Microsoft.Storage/*/read"
  ],
  "NotActions": [],
  "AssignableScopes": [
    "/subscriptions/00000000-0000-0000-0000-000000000000",
    "/subscriptions/11111111-1111-1111-1111-111111111111"
  ]
}

要将角色添加到订阅,请运行以下 PowerShell 命令:To add the role to the subscriptions, run the following PowerShell command:

New-AzRoleDefinition -InputFile "C:\CustomRoles\customrole1.json"

更新自定义角色Update a custom role

与创建自定义角色类似,可以使用 PSRoleDefinition 对象或 JSON 模板修改现有自定义角色。Similar to creating a custom role, you can modify an existing custom role using either the PSRoleDefinition object or a JSON template.

使用 PSRoleDefinition 对象更新自定义角色Update a custom role with the PSRoleDefinition object

若要修改自定义角色,请先使用 Get-AzRoleDefinition 命令检索角色定义。To modify a custom role, first, use the Get-AzRoleDefinition command to retrieve the role definition. 然后,对角色定义做出所需更改。Second, make the desired changes to the role definition. 最后,使用 Set-AzRoleDefinition 命令保存修改后的角色定义。Finally, use the Set-AzRoleDefinition command to save the modified role definition.

以下示例将 Microsoft.Insights/diagnosticSettings/* 操作添加到“虚拟机操作员”自定义角色。The following example adds the Microsoft.Insights/diagnosticSettings/* operation to the Virtual Machine Operator custom role.

$role = Get-AzRoleDefinition "Virtual Machine Operator"
$role.Actions.Add("Microsoft.Insights/diagnosticSettings/*")
Set-AzRoleDefinition -Role $role
PS C:\> $role = Get-AzRoleDefinition "Virtual Machine Operator"
PS C:\> $role.Actions.Add("Microsoft.Insights/diagnosticSettings/*")
PS C:\> Set-AzRoleDefinition -Role $role

Name             : Virtual Machine Operator
Id               : 88888888-8888-8888-8888-888888888888
IsCustom         : True
Description      : Can monitor and restart virtual machines.
Actions          : {Microsoft.Storage/*/read, Microsoft.Network/*/read, Microsoft.Compute/*/read,
                   Microsoft.Compute/virtualMachines/start/action...}
NotActions       : {}
AssignableScopes : {/subscriptions/00000000-0000-0000-0000-000000000000,
                   /subscriptions/11111111-1111-1111-1111-111111111111}

以下示例将 Azure 订阅添加到“虚拟机操作员”自定义角色的可分配范围。The following example adds an Azure subscription to the assignable scopes of the Virtual Machine Operator custom role.

Get-AzSubscription -SubscriptionName Production3

$role = Get-AzRoleDefinition "Virtual Machine Operator"
$role.AssignableScopes.Add("/subscriptions/22222222-2222-2222-2222-222222222222")
Set-AzRoleDefinition -Role $role
PS C:\> Get-AzSubscription -SubscriptionName Production3

Name     : Production3
Id       : 22222222-2222-2222-2222-222222222222
TenantId : 99999999-9999-9999-9999-999999999999
State    : Enabled

PS C:\> $role = Get-AzRoleDefinition "Virtual Machine Operator"
PS C:\> $role.AssignableScopes.Add("/subscriptions/22222222-2222-2222-2222-222222222222")
PS C:\> Set-AzRoleDefinition -Role $role

Name             : Virtual Machine Operator
Id               : 88888888-8888-8888-8888-888888888888
IsCustom         : True
Description      : Can monitor and restart virtual machines.
Actions          : {Microsoft.Storage/*/read, Microsoft.Network/*/read, Microsoft.Compute/*/read,
                   Microsoft.Compute/virtualMachines/start/action...}
NotActions       : {}
AssignableScopes : {/subscriptions/00000000-0000-0000-0000-000000000000,
                   /subscriptions/11111111-1111-1111-1111-111111111111,
                   /subscriptions/22222222-2222-2222-2222-222222222222}

以下示例将管理组添加到“虚拟机操作员”自定义角色的 AssignableScopesThe following example adds a management group to AssignableScopes of the Virtual Machine Operator custom role. 将管理组添加到 AssignableScopes 的功能目前处于预览状态。Adding a management group to AssignableScopes is currently in preview.

Get-AzManagementGroup

$role = Get-AzRoleDefinition "Virtual Machine Operator"
$role.AssignableScopes.Add("/providers/Microsoft.Management/managementGroups/{groupId1}")
Set-AzRoleDefinition -Role $role
PS C:\> Get-AzManagementGroup

Id          : /providers/Microsoft.Management/managementGroups/marketing-group
Type        : /providers/Microsoft.Management/managementGroups
Name        : marketing-group
TenantId    : 99999999-9999-9999-9999-999999999999
DisplayName : Marketing group

PS C:\> $role = Get-AzRoleDefinition "Virtual Machine Operator"
PS C:\> $role.AssignableScopes.Add("/providers/Microsoft.Management/managementGroups/marketing-group")
PS C:\> Set-AzRoleDefinition -Role $role

Name             : Virtual Machine Operator
Id               : 88888888-8888-8888-8888-888888888888
IsCustom         : True
Description      : Can monitor and restart virtual machines.
Actions          : {Microsoft.Storage/*/read, Microsoft.Network/*/read, Microsoft.Compute/*/read,
                   Microsoft.Compute/virtualMachines/start/action...}
NotActions       : {}
AssignableScopes : {/subscriptions/00000000-0000-0000-0000-000000000000,
                   /subscriptions/11111111-1111-1111-1111-111111111111,
                   /subscriptions/22222222-2222-2222-2222-222222222222,
                   /providers/Microsoft.Management/managementGroups/marketing-group}

使用 JSON 模板更新自定义角色Update a custom role with a JSON template

使用以前的 JSON 模板可以轻松修改现有的自定义角色,以便添加或删除 Actions。Using the previous JSON template, you can easily modify an existing custom role to add or remove Actions. 更新 JSON 模板,为网络添加读取操作,如以下示例所示。Update the JSON template and add the read action for networking as shown in the following example. 模板中列出的定义不是以累积方式应用到现有定义的,这意味着角色的显示方式完全符合模板中的指定。The definitions listed in the template are not cumulatively applied to an existing definition, meaning that the role appears exactly as you specify in the template. 还需使用角色的 ID 更新“ID”字段。You also need to update the Id field with the ID of the role. 如果不确定此值是什么,可以使用 Get-AzRoleDefinition cmdlet 来获取该信息。If you aren't sure what this value is, you can use the Get-AzRoleDefinition cmdlet to get this information.

{
  "Name": "Custom Role 1",
  "Id": "acce7ded-2559-449d-bcd5-e9604e50bad1",
  "IsCustom": true,
  "Description": "Allows for read access to Azure storage and compute resources and access to support",
  "Actions": [
    "Microsoft.Compute/*/read",
    "Microsoft.Storage/*/read",
    "Microsoft.Network/*/read"
  ],
  "NotActions": [],
  "AssignableScopes": [
    "/subscriptions/00000000-0000-0000-0000-000000000000",
    "/subscriptions/11111111-1111-1111-1111-111111111111"
  ]
}

若要更新现有角色,请运行以下 PowerShell 命令:To update the existing role, run the following PowerShell command:

Set-AzRoleDefinition -InputFile "C:\CustomRoles\customrole1.json"

删除自定义角色Delete a custom role

若要删除自定义角色,请使用 Remove-AzRoleDefinition 命令。To delete a custom role, use the Remove-AzRoleDefinition command.

以下示例删除了 虚拟机操作员 自定义角色。The following example removes the Virtual Machine Operator custom role.

Get-AzRoleDefinition "Virtual Machine Operator"
Get-AzRoleDefinition "Virtual Machine Operator" | Remove-AzRoleDefinition
PS C:\> Get-AzRoleDefinition "Virtual Machine Operator"

Name             : Virtual Machine Operator
Id               : 88888888-8888-8888-8888-888888888888
IsCustom         : True
Description      : Can monitor and restart virtual machines.
Actions          : {Microsoft.Storage/*/read, Microsoft.Network/*/read, Microsoft.Compute/*/read,
                   Microsoft.Compute/virtualMachines/start/action...}
NotActions       : {}
AssignableScopes : {/subscriptions/00000000-0000-0000-0000-000000000000,
                   /subscriptions/11111111-1111-1111-1111-111111111111}

PS C:\> Get-AzRoleDefinition "Virtual Machine Operator" | Remove-AzRoleDefinition

Confirm
Are you sure you want to remove role definition with name 'Virtual Machine Operator'.
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

后续步骤Next steps