DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on • Updated on

Azure DevOps YAML pipeline : Use Azure KeyVault secret as Environment Variable

I ran into an issue on the other day, when I tried to read Azure KeyVault secret via Environment Variable for my xUnit project in yaml pipeline.

There are several GitHub issues, or stack overflow posts discussing this, but in fact, it was quite straight forward at the end.

This applies any language, doesn't have to be dotnet core. But as I am C# developer, I explain everything by using C#.


I assume you already have followings.

  • Azure DevOps
  • dotnet core project
  • Azure KeyVault

Sample app

I developed very simple console app to explain. It just grab "MySecret" environment variable and compare the result. I wanted to display the value in the screen but due to security reason, which is good, Azure DevOps won't display the value.

using System;

namespace myconsoleapp
    class Program
        static void Main(string[] args)
            var mySecret = Environment.GetEnvironmentVariable("MySecret");
            if(mySecret == "IHave3Cats")
                Console.WriteLine("Correct Environment Variable");
                Console.WriteLine("Wrong Environment Variable");
Enter fullscreen mode Exit fullscreen mode

Azure KeyVault

I have a secret created in my KeyVault and set the value as "IHave3Cats".

Alt Text

I also give permission to Azure DevOps project.

Alt Text

Author pipeline

There are a couple of ways to obtain secret from Azure KeyVault, but I use pipeline task to get it this time. It should be straight forward so I won't explain how to.

This is my yaml.

- master

  vmImage: 'ubuntu-latest'

- task: AzureKeyVault@1
    azureSubscription: 'ConnectionToAzure'
    KeyVaultName: 'kenakamukeys'
    SecretsFilter: 'MySecret'
    RunAsPreJob: false

- task: DotNetCoreCLI@2
  displayName: 'build my app'
    command: 'build'
    projects: '**/*.csproj'

- task: DotNetCoreCLI@2
  displayName: 'run my app'
    MySecret: $(MySecret)
    command: 'run'
    projects: '**/*.csproj'
Enter fullscreen mode Exit fullscreen mode

The point is to use env property in task field. Once I run the pipeline, I can confirm the expected result.

Alt Text


There is an official document clearly explains this.

I can use env not only for task but also for various other types :)

Top comments (2)

lonelydev profile image

Hey @kenakamu

This works only for scripting tasks.
If you were to reference a secret param in a deployment task, Azure Pipelines seem to fail in every possible way.

kenakamu profile image
Kenichiro Nakamura

Thanks for your comment. Could you let me know a little bit more detail what do you want to do ?