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.

[Fact]
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:

resources:
- repo: self

variables:
  MyVariable: 'This is a test'

pool:
  vmImage: vs2017-win2016

steps:
- task: DotNetCoreCLI@2
  displayName: Test
  inputs:
    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.


Comments
Gravatar Sergio Navarro Pino Wednesday, February 27, 2019
Hi Scott, I have a doubt: in Azure pipelines variables are upper-cased as we can see here: https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch So in you example, you should read "MYVARIABLE" in order to properly read the value during the build test execution. I have tested it and if I read with lowercase I get a null Am I missing something? Regards
Gravatar scott Wednesday, February 27, 2019
Good catch. Are you building on a Linux pipeline? Windows uses case insensitive env variables. I was on a Windows build pipeline, so the unit test works.
Gravatar Sergio Navarro Pino Thursday, February 28, 2019
You are right, this only happens to Linux agents.
Comments are closed.