Search code examples
powershellazure-automationservice-principal

Azure Automation | Runbook | Powershell | Get-AzRoleAssignment | Microsoft.Rest.Azure.CloudException


I have an Automation account and I have set up the Run-As-Account for non-classic resources. In my automation Account I have imported Az.Resources, Az.Account, Az.Storage and Az.KeyVault.

I have a script that does not work under the Automation service principle. The following error is a first of 3;

Get-AzRoleAssignment : Exception of type 'Microsoft.Rest.Azure.CloudException' was thrown. At line:26 char:10

I have granted the application registration the following set of application api permissions in Azure Active Directory (more than I anticipate needing);

enter image description here

At the start of the script I run the Connect-AzAccount cmdlet;

 $servicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Connect-AzAccount -ServicePrincipal `
    -Tenant $servicePrincipalConnection.TenantID `
    -ApplicationId $servicePrincipalConnection.ApplicationID `
    -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint

Followed by the failing command;

    If(!(Get-AzRoleAssignment | Where-Object { $_.RoleDefinitionName -eq "Storage Blob Data Contributor" `
    -and $_.scope -eq "/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$serviceName" `
    -and $_.SignInName -eq (Get-AzContext).Account.Id})){
    # There does not exist the requisite permission for the run-as-account context, grant; 'Storage Blob Data Contributor'.
    New-AzRoleAssignment -RoleDefinitionName "Storage Blob Data Contributor" `
        -ApplicationId (Get-AzADServicePrincipal | Where-Object { $_.DisplayName -eq "jupiterautomation01" }).ApplicationId `
        -Scope "/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$serviceName"
}

I need to grant the right permissions, but do not know what they are.


Solution

  • The permissions assigned need to be consented to by an 'admin'. The button was only available when accessing Azure via the Microsoft account used to create the Active Directory tenant.

    1. Sign in with an admin account that can consent.
    2. Grant API permissions to read or read/write (i needed write as well) on Active Directory to the application.
    3. Give admin consent using the button displayed in the image.

    enter image description here