276

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.

Parker
  • 7,244
  • 12
  • 70
  • 92
Noel Yap
  • 18,822
  • 21
  • 92
  • 144

16 Answers16

241

This can be done via EnvInject plugin in the following way:

  1. Create an "Execute shell" build step that runs:

    echo AOEU=$(echo aoeu) > propsfile
    
  2. Create an Inject environment variables build step and set "Properties File Path" to propsfile.

Note: This plugin is (mostly) not compatible with the Pipeline plugin.

Fernando César
  • 681
  • 1
  • 8
  • 16
malenkiy_scot
  • 16,415
  • 6
  • 64
  • 87
  • 4
    EnvInject doesn't handle the situation I gave above: [EnvInject] - Injecting as environment variables the properties content AOEU=$(echo aoeu) [EnvInject] - Variables injected successfully. [EnvInject] - Unset unresolved 'AOEU' variable. – Noel Yap May 17 '12 at 00:32
  • It seems that I did not quite get what it was that you wanted. My meaning was that you first run a shell build step where you write something like `echo 'AOEU=' > propsfile` and then `echo \`echo aoeu\` > propsfile`. In the next build step you load propsfile (the contents of which is now `AOEU=aoeu`). – malenkiy_scot May 17 '12 at 06:13
  • 1
    That solution uses Unix shell syntax and won't work on windows. – fbmd Apr 16 '15 at 13:14
  • 2
    @fbmd I'm running it on Windows. You just need to make sure you have `sh` on the path. – Custodio Sep 17 '15 at 19:29
  • 2
    EnvInject does not work if the "execute shell" exits with an error because the build does not proceed to the injection part. – Chadi Apr 19 '16 at 07:57
  • Using the managed script is also the same result, in case if anyone is wondering. The propsFile will be under the /workspace of your project directory – Zeus Oct 10 '16 at 20:08
  • What's wrong with just adding a "Execute shell" with `export foo="bar"` ? – Vitim.us Oct 24 '19 at 01:48
  • 2
    @Vitim.us, `foo` will get exported in that specific shell action but not in other actions. – Noel Yap Feb 20 '20 at 22:48
  • Doesn't work with Maven plugin. EnvInject looks for propsfile before any pre-build step is executed. – Steve Mitchell Oct 12 '22 at 23:34
124

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

kenorb
  • 155,785
  • 88
  • 678
  • 743
kenny_k
  • 3,831
  • 5
  • 30
  • 41
  • 6
    Try setting the value based on the output of a shell command. – Noel Yap Jun 18 '15 at 23:11
  • 2
    @NoelYap Works too, as long as in the end the line evaluates to `key=value`. In my use case I generate the line completely: `cat app/build.gradle | grep "def majorVersion" | python -c 'import sys,re,os; print("VERSION_NUMBER="+re.findall(r"[\d+\.]+", sys.stdin.read())[0]+os.environ["BUILD_NUMBER"])'` – kenny_k Jun 19 '15 at 06:52
  • @theFunkyEngineer what version of EnvInject are you using? With 1.91.3, a command like yours is interpreted as "cat=app...". Would be great if this feature was supported, but I'm getting the sense that this may have worked for you by accident. – killthrush Jul 23 '15 at 20:50
  • FWIW, I did get my variables to work by creating a property file first using the Script Content box (not shown) and then reading it back in using the Path field shown in the screenshot above. It only supports hard-coded absolute paths though which is a bummer. – killthrush Jul 23 '15 at 21:25
  • @killthrush Not sure, I'm also using 1.91.3. I haven't tried with a simple `echo FOO=BAR`, but that seems like a good test of whether it would work for you. – kenny_k Jul 23 '15 at 22:18
  • @theFunkyEngineer Yeah, I tried a lot of variations of echo, printf, and eval and finally gave up. Wonder if it's a shell idiosyncracy of some kind. I'm running Jenkins 1.620 with Ubuntu 14.04. Thanks just the same - it's a tantalizing possibility that this could work! – killthrush Jul 23 '15 at 22:34
  • 1
    attempting to assign a value to the output of a shell command is not working for me either: `BUILD_DATE=date "+%Y-%m-%d-%H_%M_%S"` and `BUILD_DATE=$(date "+%Y-%m-%d-%H_%M_%S")` and `BUILD_DATE=\`date "+%Y-%m-%d-%H_%M_%S"\`` did not work for me – scottysseus Dec 11 '15 at 14:02
  • is it possible to do it globally to apply for every build? – Mando Feb 05 '16 at 15:57
  • @scottyseus did you ever solve that? Am trying to do the same. – Andy Hayden Feb 24 '17 at 08:56
  • @AndyHayden it has been a while since I last did this, but I believe my solution was to add a build step to capture the date in a file, and then I somehow injected that file into the build. – scottysseus Feb 24 '17 at 16:58
  • 1
    @scottyseus I ended up using this https://wiki.jenkins-ci.org/display/JENKINS/Environment+Script+Plugin worked like a charm. http://stackoverflow.com/a/38286383/1240268 – Andy Hayden Feb 24 '17 at 17:31
  • If I use this method, how can/do I manipulate the variable inside an "Execute shell" step? If I simply set the same variable inside the step it doesn't get set. For example if set it in one "Execute shell" step, and echo it in another "Execute shell" step, it doesn't show the changes. – Chris F Apr 29 '21 at 17:46
71

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

Parker
  • 7,244
  • 12
  • 70
  • 92
  • 2
    That is a global property. It will effect ALL jobs on Jenkins. Supposed I just want this property for one job? – IgorGanapolsky Nov 17 '16 at 21:36
  • I've added to Manage Jenkins - Configure System - Global properties, the following: `git` `/path/to/my/git` and `PATH+git` `/path/to/my/git`. However, if I am trying to access `git` from the a `Jenkins pipeline script`, I get: `/bin/sh: git: command not found`. – bsky Mar 06 '17 at 15:46
  • 1
    I just needed to set up JAVA_HOME environment variable and this answer was the one that helped me. – Sandoval0992 Jan 11 '19 at 10:24
  • @IgorGanapolsky In that case, could you use an environment variable that only that particular job would be aware of? – Parker Oct 22 '20 at 14:26
40

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

Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add
nik
  • 1,464
  • 4
  • 18
  • 32
26

You can try something like this

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

You can use Environment Injector Plugin to set environment variables in Jenkins at job and node levels. These are the steps 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.

Ayaz Alifov
  • 8,334
  • 4
  • 61
  • 56
16

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.

luka5z
  • 7,525
  • 6
  • 29
  • 52
15

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
  • Thank you! Build Env Propagator Plugin worked when I tried it, and it's great to have the ability to set environment variables during the Build steps! – twasbrillig Dec 16 '16 at 18:44
8

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).

barotdeep
  • 81
  • 1
  • 2
7

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
    
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • unfortunately did not work for me. after `sudo su - jenkins`, still `echo $USER` gives me `root`. – prayagupa May 09 '17 at 00:40
  • @prayagupd You need to simulate a full login, so use `su -l` parameter to do that, otherwise ask a separate question. – kenorb May 09 '17 at 10:49
  • @kenorb after invoking the script, how do I read env variable again? for example, this does not work sh """ source ~/load_env.sh echo "VM_NAME: $VM_NAME" echo "VM_NAME: ${VM_NAME}" """ – Mike Aug 20 '19 at 01:44
6

extending the answer of @JSixface:

To define environment variables globally for access from within all the stages of a declarative pipeline, you can add the environment section within the pipeline block.

pipeline {                                                                                               
  agent {                                                                                                
    node {                                                                                               
      label 'myAgent'                                                                                   
    }                                                                                                    
  }                                                                                                      
  environment {
    AOEU = "${sh(returnStdout: true, script: 'echo aoeu').trim()}"                
  }                                                                                                      
  stages {
    ...
  }
}                                                                                               
Wolfson
  • 1,187
  • 17
  • 22
4

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
2

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>
Community
  • 1
  • 1
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • Is there a way such as using cloudbees API or any kind of restAPI to change the value of Jenkins environment variable? – Niv Cohen Apr 28 '21 at 19:11
2

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

Sumit
  • 874
  • 9
  • 10
0

Scripted Pipeline syntax that we use is this:

env.AEOU = sh label:'set env var',
                returnStdout: true,
               script : '''#!/bin/bash
                   echo "aeou"
               '''
sh label:'checkit',
 script : '''#!/bin/bash
    echo "${AEOU}"
 '''

Note the use of triple-single-quote notation for the script parameter to the sh step. This ensures that the ${AEOU} does not get interpolated by Groovy and does get interpolated by the bash shell.

edwardTew
  • 99
  • 1
  • 4
-3

We use groovy job file:

description('')
steps {
    environmentVariables {
        envs(PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true)
    }
}
techguy2000
  • 4,861
  • 6
  • 32
  • 48