[jenkins] How to set environment variables in Jenkins?

I would like to be able to do something like:

AOEU=$(echo aoeu)

and have Jenkins set AOEU=aoeu.

The Environment Variables section in Jenkins doesn't do that. Instead, it sets AOEU='$(echo aoeu)'.

How can I get Jenkins to evaluate a shell command and assign the output to an environment variable?

Eventually, I want to be able to assign the executor of a job to an environment variable that can be passed into or used by other scripts.

The answer is


In my case, I needed to add the JMETER_HOME environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.

Manage Jenkins Global Properties


The environment variable is then available in Ant via:

<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />

This can be verified to works by adding:

<echo message="JMeter Home: ${jmeter.home}"/>

Which produces:

JMeter Home: ~/.jmeter


This is the snippet to store environment variable and access it.

node {
   withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
      stage('Select Jenkinsfile') {
          echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
          customStep script: this
      }
   }
}

Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).


You can use Environment Injector Plugin to set environment variables in Jenkins at job and node levels. Below I will show how to set them at job level.

  1. From the Jenkins web interface, go to Manage Jenkins > Manage Plugins and install the plugin.

Environment Injector Plugin

  1. Go to your job Configure screen
  2. Find Add build step in Build section and select Inject environment variables
  3. Set the desired environment variable as VARIABLE_NAME=VALUE pattern. In my case, I changed value of USERPROFILE variable

enter image description here

If you need to define a new environment variable depending on some conditions (e.g. job parameters), then you can refer to this answer.


EnvInject Plugin aka (Environment Injector Plugin) gives you several options to set environment variables from Jenkins configuration.

By selecting Inject environment variables to the build process you will get:

  • Properties File Path
  • Properties Content
  • Script File Path

  • Script Content

  • and finally Evaluated Groovy script.


Evaluated Groovy script gives you possibility to set environment variable based on result of executed command:

  • with execute method:
    return [HOSTNAME_SHELL: 'hostname'.execute().text, 
        DATE_SHELL: 'date'.execute().text,
        ECHO_SHELL: 'echo hello world!'.execute().text
    ]
  • or with explicit Groovy code:
    return [HOSTNAME_GROOVY: java.net.InetAddress.getLocalHost().getHostName(),
        DATE_GROOVY: new Date()
    ] 

(More details about each method could be found in build-in help (?))


Unfortunately you can't do the same from Script Content as it states:

Execute a script file aimed at setting an environment such as creating folders, copying files, and so on. Give the script file content. You can use the above properties variables. However, adding or overriding environment variables in the script doesn't have any impacts in the build job.


We use groovy job file:

description('')
steps {
    environmentVariables {
        envs(PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true)
    }
}

For some reason sudo su - jenkins does not log me to jenkins user, I ended up using different approach.

I was successful setting the global env variables using using jenkins config.xml at /var/lib/jenkins/config.xml (installed in Linux/ RHEL) - without using external plugins.

I simply had to stop jenkins add then add globalNodeProperties, and then restart.

Example, I'm defining variables APPLICATION_ENVIRONMENT and SPRING_PROFILES_ACTIVE to continious_integration below,

<?xml version='1.0' encoding='UTF-8'?>
<hudson>

  <globalNodeProperties>
    <hudson.slaves.EnvironmentVariablesNodeProperty>
      <envVars serialization="custom">
        <unserializable-parents/>
        <tree-map>
          <default>
            <comparator class="hudson.util.CaseInsensitiveComparator"/>
          </default>
          <int>2</int>
          <string>APPLICATION_ENVIRONMENT</string>
          <string>continious_integration</string>
          <string>SPRING_PROFILES_ACTIVE</string>
          <string>continious_integration</string>
        </tree-map>
      </envVars>
    </hudson.slaves.EnvironmentVariablesNodeProperty>
  </globalNodeProperties>
</hudson>

Try Environment Script Plugin (GitHub) which is very similar to EnvInject. It allows you to run a script before the build (after SCM checkout) that generates environment variables for it. E.g.

Jenkins Build - Regular job - Build Environment

and in your script, you can print e.g. FOO=bar to the standard output to set that variable.

Example to append to an existing PATH-style variable:

echo PATH+unique_identifier=/usr/local/bin

So you're free to do whatever you need in the script - either cat a file, or run a script in some other language from your project's source tree, etc.


You can try something like this

stages {
        stage('Build') {
            environment { 
                    AOEU= sh (returnStdout: true, script: 'echo aoeu').trim()
                }
            steps {
                sh 'env'
                sh 'echo $AOEU'
            }
        }
    }

In my case, I had configure environment variables using the following option and it worked-

Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add

There is Build Env Propagator Plugin which lets you add new build environment variables, e.g.

Jenkins Build - Propagate build environment variables

Any successive Propagate build environment variables step will override previously defined environment variable values.


The simplest way

You can use EnvInject plugin to injects environment variables at build startup. For example:

Add key=value (bash OK!) under 'Build Environment'->'Inject environment variables to the build process' -> 'Properties Content'

How you know it's working

EnvInject - Variables injected successfully


You can use either of the following ways listed below:

  1. Use Env Inject Plugin for creating environment variables. Follow this for usage and more details https://github.com/jenkinsci/envinject-plugin
    1. Navigate below and can add

Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add

enter image description here


Normally you can configure Environment variables in Global properties in Configure System.

However for dynamic variables with shell substitution, you may want to create a script file in Jenkins HOME dir and execute it during the build. The SSH access is required. For example.

  1. Log-in as Jenkins: sudo su - jenkins or sudo su - jenkins -s /bin/bash
  2. Create a shell script, e.g.:

    echo 'export VM_NAME="$JOB_NAME"' > ~/load_env.sh
    echo "export AOEU=$(echo aoeu)" >> ~/load_env.sh
    chmod 750 ~/load_env.sh
    
  3. In Jenkins Build (Execute shell), invoke the script and its variables before anything else, e.g.

    source ~/load_env.sh
    

Examples related to jenkins

Maven dependencies are failing with a 501 error Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding How to solve npm install throwing fsevents warning on non-MAC OS? Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working Error "The input device is not a TTY"

Examples related to continuous-integration

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject Jenkins vs Travis-CI. Which one would you use for a Open Source project? Continuous Integration vs. Continuous Delivery vs. Continuous Deployment How do I clone a job in Jenkins? How to trigger Jenkins builds remotely and to pass parameters How to connect Bitbucket to Jenkins properly Managing SSH keys within Jenkins for Git How to uninstall Jenkins? How to set environment variables in Jenkins? Jenkins CI: How to trigger builds on SVN commit

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter