Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we'll show the different ways to set and use environment variables in Jenkins.

To learn more about Jenkins and Pipelines, refer to our intro to Jenkins.

2. Global Properties

We can set global properties by navigating to “Manage Jenkins -> Configure System -> Global properties option”.

Let's first check the “Environment variables” checkbox and then add the variables and their respective values inside the “List of Variables” section:

This is one of the easiest and least intrusive ways to set environment variables.

3. Jenkinsfile

We can set environment variables globally by declaring them in the environment directive of our Jenkinsfile.

Let's see how to set two variables, DISABLE_AUTH and DB_ENGINE:

Jenkinsfile (Declarative Pipeline)
pipeline {
    //Setting the environment variables DISABLE_AUTH and DB_ENGINE
    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'mysql'
    }

}

This approach of defining the variables in the Jenkins file is useful for instructing the scripts; for example, a Make file.

4. EnvInject

We can install and use the EnvInject plugin to inject environment variables during the build startup.

In the build configuration window, we select the “Inject environment variables” option in the “Add build step” combo box.

We can then add the required environment variables in the properties content text box.

For example, we can specify the user profile:

5. Usage

Now, we can use any of our environment variables by surrounding the name in ${}:

echo "Database engine is ${DB_ENGINE}"

6. Conclusion

In this article, we saw how to set and use environment variables in Jenkins.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!