Accessing Key Vault from DevOps pipelines
Code requires access
If your code requires access to Key Vault, for example, running integration tests as part of your build pipeline, do the following:
- Using the DevOps project settings, create an Azure Resource Manager service connection using Service Principal Authentication. Docs.
- Add an access policy to your Key Vault on Azure, giving the service principal Get and List permissions for secrets (or whichever other permissions your code requires).
- Configure your integration tests to run as an Azure CLI task in the build pipeline. You may want to split your unit tests and integration tests into two tasks. Unfortunately, using the CLI task does not publish the test results to DevOps, so you may also want to configure a third task that combines unit and integration test results. The
$(azureServiceConnection)variable contains the name of the service connection which you created in step 1.
- task: DotNetCoreCLI@2
displayName: 'Run Unit Tests'
arguments: '--configuration $(buildConfiguration) --logger trx --results-directory $(Common.TestResultsDirectory)'
- task: AzureCLI@1
displayName: 'Run Integration Tests'
inlineScript: 'dotnet test $(Build.SourcesDirectory)/*IntegrationTests/*.csproj --configuration $(buildConfiguration) --logger trx --results-directory $(Common.TestResultsDirectory)'
- task: PublishTestResults@2
displayName: 'Publish Test Results'
Original source: https://stackoverflow.com/a/56863107
Pipeline requires access
If your pipelines require access to secrets in the Key Vault, for example, if you need deploy resources with secrets in their configuration, one way might be to fetch the secrets during the build or deployment, but this could leak secrets by logging them during the build process. The way around this is to use Key Vault references, which will only resolve the secret within the Azure environment once the resource is deployed. For example, if you need to set a secret as an environment variable for an App Service, add something like following to the App settings field in your Azure App Service deploy task (App settings take the form "-KEY value"):
This will pass the entire
@Microsoft.KeyVault(SecretUri=https://your-project-key-vault.vault.azure.net/secrets/super-secret-variable/instance) string to the Azure configuration, and does not resolve the secret during pipeline execution.