OdeToCode IC Logo

Using Environment Variables in Azure DevOps Pipelines

Friday, February 8, 2019

Imagine you have a unit test that depends on an environment variable.

public void CanGetMyVariable()
    var expected = "This is a test";
    var actual = Environment.GetEnvironmentVariable("MYVARIABLE");

    Assert.Equal(expected, actual);

Of course the dependency might not be so explicit. You could have a test that calls into code, that calls some other code, and the other code needs an environment variable. Or, maybe you have a script or tool that needs an environment variable. The question is - how do you setup environment variables in a DevOps pipeline?

The answer is easy - when a pipeline executes, Azure will place all pipeline variables into environment variables, so any tools, scripts, tasks, or processes you run as part of the build can access parameters through the environment.

In other words, I can make the above test pass by defining a variable in my pipeline YAML definition:

- repo: self

  MyVariable: 'This is a test'

  vmImage: vs2017-win2016

- task: DotNetCoreCLI@2
  displayName: Test
    command: test
    projects: '**/*[Tt]ests/*.csproj  '
    arguments: '--configuration $(BuildConfiguration)'

... Or in the DevOps pipeline GUI:

Setting DevOps Pipeline Variable

Also included are the built-in variables, like Build.BuildNumber and System.AccessToken. Just be aware that the variable names you use to reference these parameters can depend on the context. See Build Variables for more details.