Search code examples
jenkinsjenkins-pipeline

How to set and get LINUX ENV variables in Jenkins pipelines?


This might be a stupid question, but I'm unable to solve it. I would like to set and get LINUX (not Jenkins) ENV variables. I'm aware how to deal with Jenkins environment variables (e.g. env.JENKINS_HOME) but Linux ENV variables seem to be closed off.

When using sh "printenv" then this prints all Linux ENV variables as expected, but setting them via export SOME_VAR=123 doesn't seem to work. printenv isn't showing it. Using System.getenv("SOME_VAR") also doesn't work.

For example:

stage('echo stuff') {
    steps {
        script {
            sh "printenv"
            sh "export SOME_VAR=123"
            sh 'echo $SOME_VAR'
        }
    }
}

Produces this:

[Pipeline] stage
[Pipeline] { (echo stuff)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ export SOME_VAR=123
+ SOME_VAR=123
[Pipeline] sh
+ echo

[Pipeline] }

I wasn't able to find help on this presumably very common problem, because everything available deals with Jenkins environment variables.


Solution

  • I think the problem is, that every sh-block is its own shell session. So if you export a variable with sh "export SOME_VAR=123" it is not set in the next line. You want to use shell multi-line like this:

    stage('echo stuff') {
      steps {
        script {
            sh '''
              export SOME_VAR=123
              echo $SOME_VAR
            '''
        }
      }
    }
    

    This will work as you expect.

    More info can be found Jenkins.io running-multiple-steps