Using environment variables in the DevOps pipeline

Rituparna Goswami Mishra
medialesson

--

Introduction

There can be several reasons why a developer might need to use environment variables. Implementing the same in the local machine is straight forward but how do we do it in the DevOps pipeline? Let’s find out. In this blog, we will be using an environment variable “RunLiveTests” as an example, to indicate our program when to run a specific set of tests. We are using c# as our programming language in this blog.

Creating the configuration to read the environment variables

We create a static shared class named “HelperClass” and in there, we are writing a function, “GetConfiguration”, that will return configuration whenever it’s called.

public static Microsoft.Extensions.Configuration.IConfiguration GetConfiguration()
{
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
return configuration;
}

Use the configuration values

To use the configuration, we call the function created in the previous step. Then we store the configuration in a local variable. Next, we use the key of the environment variable to read the value, which is “RunLiveTests” in our case.

var config = HelperClass.GetConfiguration();
if(config[“runLiveTests”] == “true”)
{
// run the specific test case
}

Add the environment variables in the local system

To add the environment variable in local machine, go to the “run” and write “env” and it will give quick access to edit environment variables. We edit the environment variables to add our values. We might need to restart the IDE for it to read the newly added/changed values.

Add the environment variable in the DevOps Pipeline

In Azure DevOps, go to the “pipelines” and then go to the “library”. Add a variable group if there isn’t one. And then add the variable “key/name” and the “value” to the variables section of the group and click on “save”. In our example, we are adding variable group named “TestVariableGroup”.

Modifying the pipeline YAML file to add the variable group.

Now we go to the “azure-pipelines.yml” of our project, and add the variable group name to the specific job that need to consume the variables value from group.

- job: BackendTests
variables:
- group: TestVariableGroup

That’s it, now we are all set to use environment variables from local machine as well as Azure pipelines for our project.

Conclusion

Apart from system environment variables, we can always store these values in in our “user secrets” file and use them in combination with appSettings” file. Let you know, if you want us to write a blog post on this topic. Thanks for reading. Check out my other posts.

--

--