Search code examples
azureazure-devopsazure-pipelines

Make Azure Keyvault secrets available in entire pipeline


In order to access my secret from the keyvault, I run

        - task: AzureKeyVault@2
          inputs:
            azureSubscription: $(KEYVAULT_SC_DEV)
            KeyVaultName: $(KEYVAULT_NAME_DEV)
            SecretsFilter: APICREDENTIALS
            RunAsPreJob: true 

which works fine.

However, I have multiple jobs and am now facing the trouble of having to repeat these lines too many times.

So, is there a way to tell Azure Devops that this secret should be set globally for each job/stage/step.. etc?


Solution

  • If you want these secrets available to multiple pipelines one way would be to use the library variables

    enter image description here

    And reference these in your pipeline https://learn.microsoft.com/en-us/azure/devops/pipelines/library/variable-groups?view=azure-devops&tabs=yaml#use-a-variable-group

    If you want these secrets available to multiple stages/jobs/steps within the same pipeline one way would be to create a pipeline variable

    variables:
      secretValue: ''
    
    jobs:
    - job: RetrieveSecret
      steps:
      - task: AzureKeyVault@2
        inputs:
          azureSubscription: $(KEYVAULT_SC_DEV)
          KeyVaultName: $(KEYVAULT_NAME_DEV)
          SecretsFilter: APICREDENTIALS
          OutputVariable: secretValue
    

    Here the RetrieveSecret job retrieves the secret from the Key Vault and stores it in the secretValue pipeline variable.Once the secret has been stored in the pipeline variable, you can reference it from any job or task in your pipeline by using the $(pipelineVariableName) syntax.

    The caveat here is that pipeline variables are scoped to a specific job, if you wanted to use the same variable across different jobs then you need to pass this value to the next job sort of like below

    jobs:
    - job: Job1
      steps:
      - task: AzureKeyVault@2
        inputs:
          azureSubscription: $(KEYVAULT_SC_DEV)
          KeyVaultName: $(KEYVAULT_NAME_DEV)
          SecretsFilter: APICREDENTIALS
          OutputVariable: secretValue
    - job: Job2
      inputs:
        secretInput: $(secretValue)
      steps:
      - task: SomeTask
        inputs:
          secret: $(secretInput)