Search code examples
powershellazure-devopsazure-powershellazure-pipelines-yaml

Powershell Script New-AzRoleAssignment with Azure Devops: Operation returned an invalid status code 'Forbidden'


I am trying to assign "Storage Blob Data Contributor" permissions to the storage account with Azure Devops Pipeline.

I have the configuration:

  • Service Connection : TestSubscription
  • The service connection is member of a group which has contributor RBAC from the subscription level
  • The service connection is created with workloadIdentity.

I am using the Azure Devops task below

- task: AzurePowerShell@5
  displayName: "Set Permissions Storage Account for Service Principal"
  inputs:
    azureSubscription: 'TestSubscription'
    ScriptType: 'FilePath'
    ScriptPath: '$(Pipeline.Workspace)/drop/Scripts/SetStoragePermission.ps1'
    ScriptArguments: '-ResourceGroup $(ResourceGroup) -StorageAccountNameStaticWebApp $(StorageAccountNameStaticWebApp) -ClientIDAppRegistration $(ClientIDAppRegistration) -IDTestSubscription $(IDTestSubscription)'
    azurePowerShellVersion: 'LatestVersion'

The script is:

param(

    [string]$ClientIDAppRegistration,
    [string]$IDTestSubscription,
    [string]$StorageAccountNameStaticWebApp,
    [string]$ResourceGroup

)


New-AzRoleAssignment -ApplicationId $ClientIDAppRegistration -RoleDefinitionName "Contributor" -Scope "/subscriptions/$($IDTestSubscription)/resourceGroups/$($ResourceGroup)/providers/Microsoft.Storage/storageAccounts/$($StorageAccountNameStaticWebApp)/"

I have another repository where this is working. With the same configuration. But in a different repository with the same service connection and same task it is giving me the error.


Solution

  • The AzurePowerShell@5 used the service principal from service connection to assign the role on the storage account. The Forbidden indicates the service principal permission is not enough.

    As you have done, you can fix it by assigning the role Storage Blob Data Contributor role to the service principal from the subscription scope.

    For the devops task, i can reproduce the same error when service principal is contributor on the subscription and resource group.

    enter image description here

    To fix the error, you can add the service principal as the User access Administrator on the resource group.

    enter image description here

    The pipeline succeeds, and the permission contributor added:

    enter image description here

    As you are trying to add Storage Blob Data Contributor permissions to the storage account, please change -RoleDefinitionName value as "Storage Blob Data Contributor" in your powershell script.

    Run the task again and the Storage Blob Data Contributor permissions added for service principal on storage account.

    enter image description here