Fork us on GitHub

Using environment variables

Table of Contents

Environment variables can be set globally, like the example below, or per stage. As you might expect, setting environment variables per stage means they will only apply to the stage in which they’re defined.

Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any

    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'sqlite'

    stages {
        stage('Build') {
            steps {
                sh 'printenv'

This approach to defining environment variables from within the Jenkinsfile can be very useful for instructing scripts, such as a Makefile, to configure the build or tests differently to run them inside of Jenkins.

Another common use for environment variables is to set or override "dummy" credentials in build or test scripts. Because it’s (obviously) a bad idea to put credentials directly into a Jenkinsfile, Jenkins Pipeline allows users to quickly and safely access pre-defined credentials in the Jenkinsfile without ever needing to know their values.

Credentials in the Environment

If your Jenkins environment has credentials configured, such as build secrets or API tokens, those can be easily inserted into environment variables for use in the Pipeline. The snippet below is for "Secret Text" type Credentials, for example.

environment {
    AWS_ACCESS_KEY_ID     = credentials('AWS_ACCESS_KEY_ID')

Just as the first example, these variables will be available either globally or per-stage depending on where the environment directive is located in the Jenkinsfile.

The second most common type of Credentials is "Username and Password" which can still be used in the environment directive, but results in slightly different variables being set.

environment {
   SAUCE_ACCESS = credentials('sauce-lab-dev')

This will actually set 3 environment variables:

  • SAUCE_ACCESS containing <username>:<password>

  • SAUCE_ACCESS_USR containing the username

  • SAUCE_ACCESS_PSW containing the password

credentials is only available for Declarative Pipeline. For those using Scripted Pipeline, see the documentation for the withCredentials step.

Thus far we have concerned ourselves with creating a Pipeline that is configured and executes the way we might expect. In the next couple sections, we’ll cover another crucial aspect of continuous delivery: surfacing feedback and information.