Working with the environment

1 minute read

Jenkins Pipeline exposes environment variables via the global variable env, which is available from anywhere within a Jenkinsfile. The full list of environment variables accessible from within Jenkins Pipeline is documented at http://localhost:8080/pipeline-syntax/globals#env, assuming a Jenkins controller is running on localhost:8080, and includes:

BUILD_ID

The current build ID, identical to BUILD_NUMBER for builds created in Jenkins versions 1.597+

JOB_NAME

Name of the project of this build, such as "foo" or "foo/bar".

JENKINS_URL

Full URL of Jenkins, such as http://example.com:port/jenkins/ (NOTE: only available if Jenkins URL is set in "System Configuration".)

Referencing or using these environment variables can be accomplished like accessing any key in a Groovy Map, for example:

Declarative syntax
Scripted syntax
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
            }
        }
    }
}
node {
    echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
}

Setting environment variables

Setting an environment variable within a Jenkins Pipeline is accomplished differently depending on whether Declarative or Scripted Pipeline is used.

Declarative Pipeline supports an environment directive, whereas users of Scripted Pipeline must use the withEnv step.

Declarative syntax
Scripted syntax
pipeline {
    agent any
    environment { (1)
        CC = 'clang'
    }
    stages {
        stage('Example') {
            environment { (2)
                DEBUG_FLAGS = '-g'
            }
            steps {
                sh 'printenv'
            }
        }
    }
}
1 An environment directive used in the top-level pipeline block will apply to all steps within the Pipeline.
2 An environment directive defined within a stage will only apply the given environment variables to steps within the stage.
node {
    /* .. snip .. */
    withEnv(["PATH+MAVEN=${tool 'M3'}/bin"]) {
        sh 'mvn -B verify'
    }
}