在 Azure Powershell 中将 Get-AzureRmRoleAssignment 作为服务主体执行

Execute Get-AzureRmRoleAssignment as Service Principal in Azure Powershell

在我的 MSDN Azure 订阅上,执行 Login-AzureRMAccount 后登录,我可以毫无问题地执行 Get-AzureRmRoleAssignment

我使用 powershell(New-AzureRmADApplication、New-AzureRmADServicePrincipal 和 New-AzureRmRoleAssignment)创建了一个在 Azure 中具有角色的应用程序和服务主体,并在使用这些凭据通过此 powershell 登录后:

$psCredential = New-Object System.Management.Automation.PSCredential("98349834-8494-4813-9282-4343434", (ConvertTo-SecureString "myPassword" -AsPlainText -Force))
Add-AzureRMAccount -ServicePrincipal -Tenant "123456-d5bb-44f8-a283-34534434" -Credential $psCredential

以下可以执行成功:

Get-AzureRmADApplication -IdentifierUri "http://SP.5656645-408c-4980-950e-898989"

但是执行时

Get-AzureRmRoleAssignment -debug

我遇到以下异常:

Microsoft.Rest.Azure.CloudException: Access denied to the specified API version

似乎很多人都有这个例外,我已经阅读了很多解决方案,例如在 Azure 门户中授予访问权限,(但似乎没有任何效果): 同样在授予应用程序以下权限后,仍然会引发异常:

我应该怎么做才能让服务主体执行 Get-AzureRmRoleAssignment?

编辑: 该应用程序具有所有者角色。我使用以下 ps 脚本来创建应用程序、服务主体和角色。

param
(
    [Parameter(Mandatory=$true, HelpMessage="Enter Azure Subscription name. You need to be Subscription Admin to execute the script")]
    [string] $subscriptionName,

    [Parameter(Mandatory=$true, HelpMessage="Provide a password for SPN application that you would create")]
    [string] $password,    
Mandatory=$false, HelpMessage="Provide a SPN role assignment")]
    [string] $spnRole = "owner"
)

#Initialize
$ErrorActionPreference = "Stop"
$VerbosePreference = "SilentlyContinue"
$userName = $env:USERNAME
$newguid = [guid]::NewGuid()
$displayName = [String]::Format("SP.{0}.{1}", $resourceGroupName, $newguid)
$homePage = "http://" + $displayName
$identifierUri = $homePage


#Initialize subscription
$isAzureModulePresent = Get-Module -Name AzureRM* -ListAvailable
if ([String]::IsNullOrEmpty($isAzureModulePresent) -eq $true)
{
    Write-Output "Script requires AzureRM modules to be present. Obtain AzureRM from https://github.com/Azure/azure-powershell/releases. Please refer https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DeployAzureResourceGroup/README.md for recommended AzureRM versions." -Verbose
    return
}

Import-Module -Name AzureRM.Profile
Write-Output "Provide your credentials to access Azure subscription $subscriptionName" -Verbose
Login-AzureRmAccount -SubscriptionName $subscriptionName
$azureSubscription = Get-AzureRmSubscription -SubscriptionName $subscriptionName
$connectionName = $azureSubscription.SubscriptionName
$tenantId = $azureSubscription.TenantId
$id = $azureSubscription.SubscriptionId


#Create a new AD Application
Write-Output "Creating a new Application in AAD (App URI - $identifierUri)" -Verbose
$azureAdApplication = New-AzureRmADApplication -DisplayName $displayName -HomePage $homePage -IdentifierUris $identifierUri -Password $password -Verbose
$appId = $azureAdApplication.ApplicationId
Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose


#Create new SPN
Write-Output "Creating a new SPN" -Verbose
$spn = New-AzureRmADServicePrincipal -ApplicationId $appId
$spnName = $spn.ServicePrincipalNames
Write-Output "SPN creation completed successfully (SPN Name: $spnName)" -Verbose


#Assign role to SPN
Write-Output "Waiting for SPN creation to reflect in Directory before Role assignment"
Start-Sleep 20
Write-Output "Assigning role ($spnRole) to SPN App ($appId)" -Verbose
New-AzureRmRoleAssignment -RoleDefinitionName $spnRole -ServicePrincipalName $appId 
Write-Output "SPN role assignment completed successfully" -Verbose


#Print the values
Write-Output "`nCopy and Paste below values for Service Connection" -Verbose
Write-Output "***************************************************************************"
Write-Output "Connection Name: $connectionName(SPN)"
Write-Output "Subscription Id: $id"
Write-Output "Subscription Name: $connectionName"
Write-Output "Service Principal Id: $appId"
Write-Output "Service Principal key: <Password that you typed in>"
Write-Output "Tenant Id: $tenantId"
Write-Output "***************************************************************************"

为此,您需要分配执行该操作的权限 ;) 该权限称为 Microsoft.Authorization/roleAssignments/read,您可以使用 Get-AzureRmProviderOperation Microsoft.Authorization/* 获取权限列表,要分配权限,您需要创建自定义角色定义并分配它,或者使用其中一个内置角色。

https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-control-custom-roles

我可以确认这仅发生在 powershell 中(最有趣的是 - Get-AzureRmRoleDefinition 有效,而 Get-AzureRmRoleAssignment 无效),python 代码可以在使用时列出角色分配相同的服务主体

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.authorization import AuthorizationManagementClient
tenant_id = 'tenant_guid'
application_id = 'application_guid'
application_secret = 'application_secret'
cred = ServicePrincipalCredentials(client_id=application_id, secret=application_secret, tenant=tenant_id)
client = AuthorizationManagementClient(cred, 'subscription_guid')
roles = client.role_assignments.list()
for role in roles:
    print(role)