Friday, December 27, 2024
Google search engine
HomeGuest BlogsJenkins Environment Variables: Ultimate Guide

Jenkins Environment Variables: Ultimate Guide

Introduction

Jenkins is an open-source solution used to automate different parts of the software development life cycle (SDLC). Environment variables provide a valuable tool for this, allowing developers to invoke a value multiple times without the need to define it before each use.

In this tutorial, we will cover different ways to list and set Jenkins environment variables.

Jenkins environment variablesJenkins environment variables

Prerequisites

What are Environment Variables in Jenkins?

Environment variables are global key-value pairs Jenkins can access and inject into a project. Use Jenkins environment variables to avoid having to code the same values for each project.

Other benefits of using Jenkins environment variables include improved security. Jenkins can use security credentials as variables, keeping sensitive or user-generated data out of the project code.

Note: Follow the link to our article to learn how to secure a CI/CD pipeline.

Commonly used variable types in Jenkins include env (environment variables), currentBuild, params (parameters), and docker (access to Docker functions). Jenkins saves all current environment variables in list form.

How to See Environment Variables in Jenkins

There are two ways to list all Jenkins environment variables:

  • Accessing the list through a web browser.
  • Using Jenkins shell commands to print it out.

Via env-vars.html

To see a list of Jenkins environmental variables in a web browser, navigate to the following address:

[Jenkins URL]/env-vars.html

The Jenkins URL is a combination of your system’s hostname and the port used by Jenkins. For instance, when logging in on your system using the default port 8080:

http://localhost:8080/env-vars.html
Listing Jenkins environment variables in your browserListing Jenkins environment variables in your browser

Via set/printenv Shell Command

Another method is to create a Jenkins job that executes a shell command to view environment variables. The console output of this job is a modified version of the environment variables list.

1. On the left-hand side of the Jenkins dashboard, click New Item.

Create a new item in JenkinsCreate a new item in Jenkins

2. Enter the name Environment Variables in the appropriate field and select Pipeline as the item type.

3. Click OK to confirm.

Select the Pipeline item type and set a nameSelect the Pipeline item type and set a name

4. Scroll down to the Pipeline section and add the following code:

pipeline{
    agent any
    
    stages{
        stage("Env Variables"){
            steps{
                bat "set"                                                     
            }
        }
    }
}

Note: The bat "set" command shows environment variables in Windows. If you are working in Linux/Unix, use sh "printenv".

4. Click Save to confirm changes to the pipeline.

5. Click the Build Now link on the left-hand side to create a new pipeline build.

Create a new pipeline buildCreate a new pipeline build

6. Under Build History, click the build number to access build options.

Open the new build in the Build History sectionOpen the new build in the Build History section

7. Click Console Output on the left-hand side.

Access the build console outputAccess the build console output

The Console Output page displays the output of the shell command. In this case, it is a list of Jenkins environment variables:

Jenkins environment variables listed as build console outputJenkins environment variables listed as build console output

Note: Check out our easy guide on how to set up your first build job in Jenkins.

How to Read Environment Variables in Jenkins Pipeline

There are two ways to read and access Jenkins environment variables:

  • Using the env object with the variable name.
  • Using the short variable name.

As an example, we are using the BUILD_NUMBER variable, which contains the current pipeline build number. This code demonstrates both methods of reading the variable:

pipeline {
    agent any

    stages {
        stage("Env Variables") {
            steps {
                echo "The current build number is ${env.BUILD_NUMBER}"
                echo "Another method is to use \${BUILD_NUMBER}, which is ${BUILD_NUMBER}"
            }
        }
    }
}

In the example above, Jenkins is reading the variable with:

  • ${env.BUILD_NUMBER}: Using the env object.
  • ${BUILD_NUMBER}: Using the short variable name.

Note: It is generally better to use the env object when reading environment variables since this reduces the chance of confusing the short variable name with another object.

The output displays the current build number as a result:

Console output when reading Jenkins environment variablesConsole output when reading Jenkins environment variables

How to Set Environment Variable in a Jenkins Pipeline

Users can set Jenkins environment variables on a global or local level. Add global environment variables through the Jenkins dashboard, while local variables are added using declarative, imperative, and scripted pipelines.

Jenkins Global Environment Variables

In Jenkins, any pipeline or job can access and read global environment variables. To add a new global environment variable using the Jenkins dashboard:

1. On the left-hand side of the Jenkins dashboard, click Manage Jenkins.

Open Jenkins settingsOpen Jenkins settings

2. Under the System Configuration section, click Configure System.

Under the System Configuration section, click Configure SystemUnder the System Configuration section, click Configure System

3. Scroll down until you reach the Global properties section. Check the box next to Environment variables and click the Add button to add a new variable.

4. Enter the name and value of the new variable in the appropriate fields.

Enable environment variables in the Global properties section and add a new variableEnable environment variables in the Global properties section and add a new variable

5. Click the Save button to save the new variables.

Jenkins Local Environment Variables

You can set a local environment variable in Jenkins using the declarative pipeline. This method uses the environment {} block syntax:

environment {
    [variable name] = "[variable value]"
}

Placing this block inside of the pipeline means the variable is available for use at any step of the pipeline. Placing it at a particular stage means it is only available during the steps of that stage and that stage only.

Another method is to use an env object in a script to imperatively define an environment variable:

script {
    env. [variable name] = "[variable value]"
}

Finally, using a withEnv([]) {} block sets a local environment variable as part of a scripted pipeline:

withEnv(["[variable name]= [variable value]"])

As an example, this code uses all three methods outlined above in a single pipeline to set local environment variables:

pipeline {
    agent any

    environment {
        DATE = "December 17th"
    }

    stages {
        stage("Env Variables") {
            environment {
                NAME = "Alex"
            }

            steps {
                echo "Today is ${env.DATE}"
                echo "My name ${env.NAME}"

                script {
                    env.WEBSITE = "phoenixNAP KB"
                }

                echo "This is an example for ${env.WEBSITE}"

                withEnv(["TEST_VARIABLE=TEST_VALUE"]) {
                    echo "The value of TEST_VARIABLE is ${env.TEST_VARIABLE}"
                }
            }
        }
    }
}

In this example, we are setting the DATE and NAME environment variables declaratively. DATE is at the top of the pipeline and can be used in every stage, while NAME is in the "Env Variables" stage, so we can only use it within that stage. The WEBSITE variable is set imperatively, and TEST_VARIABLE is a part of a scripted pipeline.

The console output for this pipeline shows that Jenkins is able to successfully access and read every variable:

Console output when adding local variablesConsole output when adding local variables

Injecting Environment Variables

Adding the EnvInject plugin to Jenkins allows you to inject environment variables during the build startup. This is particularly useful when creating a freestyle project in Jenkins.

Follow the steps outlined below to add the EnvInject plugin to Jenkins and inject variables:

1. Click Manage Jenkins on the left-hand side of the dashboard.

Open Jenkins settingsOpen Jenkins settings

2. In the System Configuration section, click the Manage Plugins button.

In the System Configuration section, click the Manage Plugins buttonIn the System Configuration section, click the Manage Plugins button

3. Under the Available tab, search for envinject. Mark the checkbox next to the Environment Injector plugin and click Install without restart.

Search and install the Environment Injector pluginSearch and install the Environment Injector plugin

4. Once the plugin finishes installing, return to the dashboard. Click the New Item link to create a new project, add a name, and select the Freestyle project type.

5. Click OK to create a new project.

Create a new Freestyle project type itemCreate a new Freestyle project type item

6. Scroll down to the Build section and click Add Build Steps to open a drop-down menu with available options. Select Inject environment variables.

Click Add Build Steps and select Inject environment variablesClick Add Build Steps and select Inject environment variables

7. If you want to add environment variables from a properties file, add the path to the file in the Properties File Path field. Another option is to add the new variables directly to the Properties Content field, using the [variable name] = [variable value] syntax.

Add a new environment variable in the Properties Content fieldAdd a new environment variable in the Properties Content field

8. Click the Save button to confirm adding the new environment variable. Building the project shows the variable injection in the console output.

How to Override Environment Variable in Jenkins

The Jenkins pipeline allows users to override environment variables, changing the current value of the variable with a new one.

The override process follows several rules when determining variable priority:

  • The withEnv([]) { } block overrides any environment variable.
  • Variables set using the env object cannot override those set using the environment {} block.
  • Variables set using the env object can only override other variables set with the env object.

Conclusion

After following this tutorial, you should be able to set global and local environment variables in Jenkins and review the list of currently available environment variables.

Several development teams working on multiple projects in a complex microservices environment can be a strain on limited resources. Jenkins can help you deliver a flawless final product on schedule. Learn how to install Jenkins on Kubernetes cluster to start automating a large portion of the software development process.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments