loading...

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

kenakamu profile image Kenichiro Nakamura ・2 min read

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#.

Setup

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("Corrent Environment Variable");
            else
                Console.WriteLine("Wrong Environment Variable");
        }
    }
}

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.

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

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

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

- task: DotNetCoreCLI@2
  displayName: 'run my app'
  env:
    MySecret: $(MySecret)
  inputs:
    command: 'run'
    projects: '**/*.csproj'

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

Alt Text

Summary

There is an official document clearly explains this.

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

Discussion

pic
Editor guide