在Azure中创建新角色分配时出错

时间:2017-09-15 13:51:08

标签: azure azure-powershell azure-resource-manager

对于给定的Azure订阅,我想将自定义角色分配给Service Principal。为了实现这一点,我首先检查订阅中是否存在自定义角色定义。如果角色不存在,我更新角色定义的可分配范围以包括此订阅。我正面临着#RoleDefinitionDoesNotExist'我尝试分配角色时间歇性地出错。我该如何解决这个问题?

我的代码:

$roleDef = Get-AzureRmRoleDefinition -Name $azureRmRole
if($roleDef -eq $null)
{
    Select-AzureRmSubscription -SubscriptionName $prodSubscription
    #Role definition exists in $prodSubscription
    $newRole = Get-AzureRmRoleDefinition -Name $azureRmRole
    #$scope = '/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx'
    $newRole.AssignableScopes.Add($scope)
    $def = Set-AzureRmRoleDefinition -Role $newRole
    # I have verified that role definition is updated
}

Select-AzureRmSubscription -SubscriptionName $SubscriptionName
New-AzureRmRoleAssignment -RoleDefinitionName $azureRmRole -ObjectId $SPNid -Scope $scope

错误:

  

New-AzureRmRoleAssignment:具有ID' xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'的指定角色定义不存在。   在C:\ Untitled1.ps1:71 char:1   + New-AzureRmRoleAssignment -RoleDefinitionName $ azureRmRole -ObjectId ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:CloseError:(:) [New-AzureRmRoleAssignment],CloudException       + FullyQualifiedErrorId:Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand

1 个答案:

答案 0 :(得分:0)

您应该定义自定义角色,如下所示:

{
  "Name": "Virtual Machine Power Manager",
  "IsCustom": true,
  "Description": "Can monitor, stop, start and restart v2 ARM virtual machines.",
  "Actions": [
    "Microsoft.Storage/*/read",
    "Microsoft.Network/*/read",
    "Microsoft.Compute/*/read",
    "Microsoft.Compute/virtualMachines/start/action",
    "Microsoft.Compute/virtualMachines/powerOff/action",    
    "Microsoft.Compute/virtualMachines/deallocate/action",
    "Microsoft.Compute/virtualMachines/restart/action",
    "Microsoft.Authorization/*/read",
    "Microsoft.Resources/subscriptions/resourceGroups/read",
    "Microsoft.Insights/alertRules/*",
    "Microsoft.Insights/diagnosticSettings/*",
    "Microsoft.Support/*"
  ],
  "NotActions": [

  ],
  "AssignableScopes": [
    "/subscriptions/c25b1c8e-xxxx-1111-abcd-1a12d7012123"
  ]
}

根据你的描述,你的角色定义可能是错误的,你最好检查一下。

如果要为服务主体提供自定义角色,请尝试使用以下cmdlet。

New-AzureRmRoleAssignment -ServicePrincipalName "https://shuiweb.azurewebsites.net" `
                          -RoleDefinitionName 'Virtual Machine Power Manager' `
                          -Scope '/subscriptions/*******'

enter image description here

blog:AZURE AUTOMATION RUNBOOKS WITH AZURE AD SERVICE PRINCIPALS AND CUSTOM RBAC ROLES会有所帮助。