azureazure-devopsazure-powershellazure-pipelines-release-pipelineazure-pipelines-release-task

Assign Key Vault Secrets to an Azure Function using Azure PowerShell


I am trying to automate the creation of certain azure resources via an Azure PowerShell script that is triggered from an Azure DevOps release pipeline. I want to create a function app, and automatically integrate reading right access to secrets in an already existing Key Vault. This Key Vault is in the same Azure subscription.

While I can create most resources following the documentation, there seems to be a lack of documentation regarding the creation of certain resources using Azure PowerShell (or I can't find it).

If I follow the sample from this link, I can accomplish it without a problem by using the UI in the Azure Portal, but I can't find any documentation on Microsoft Docs to do it using PowerShell.

    Write-Host "Creating Function App..."
    $fnApp = New-AzFunctionApp   -Name $functionAppName `
                        -ResourceGroupName $emailFunctionRg `
                        -Location "$(AzureRegion)" `
                        -StorageAccount $storageName `
                        -Runtime dotnet `
                        -FunctionsVersion '3' `
                        -IdentityType SystemAssigned
    Write-Host "Function App created!"

    Write-Host "Assigning Key Vault access..."
    $appId = Get-AzADServicePrincipal -DisplayName $functionAppName
    Set-AzKeyVaultAccessPolicy -VaultName EmailSettings -ServicePrincipalName $appId -PermissionsToSecrets Get,List
    Write-Host "Key Vault access granted!"

Running Set-AzKeyVaultAccessPolicy fails with "Insufficient privileges to complete the operation.". But I am not sure if this is the right path to follow, it was just a guess, based on the available functions in the documentation.

Any ideas?


Solution

  • Two potential issues to check out here:

    1. your app creation assigns the result to $fnApp. perhaps $fnApp or as commented above, $fnApp.ApplicationId is what you should be using for the -ServicePrincipalName parameter on the access policy grant.
    2. you don't have privileges to assign RBAC roles. Go to the Key Vault, choose Access Control, then click the Role Assignments tab and verify that your user appears in the list as an Administrator, User Access Administrator, or Owner.

    Edit: With respect to the RBAC privilege, since this is running in Azure Powershell from Azure DevOps, you need to check the role assignment for the Service Connection's service principal - under Azure Active Directory in the Azure Portal, look up the principal used to create the service connection, and make sure THAT gets the correct Role on the key vault.