Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 40 ยท Pipeline as Code

Environment Variables and Parameters

Use built-in variables like BUILD_NUMBER and GIT_COMMIT, the environment block, withEnv and build parameters, and learn which value wins when names collide.

A pipeline rarely does exactly the same thing every time. It needs to know which build it is, which commit it is building, where to deploy and whether to run the slow tests. Jenkins gives you two tools for that: environment variables (values the pipeline or Jenkins sets) and parameters (values a person or another job chooses when starting a build).

This lesson shows the built-in variables, the environment block, the parameters directive, withEnv, and the rules for which value wins. The real behaviour needs a Jenkins server, so those examples are read-only. A JavaScript stand-in then models the resolution rules and the famous "boolean becomes a string" surprise.

Where values come from

Jenkins built-ins BUILD_NUMBER, JOB_NAME, WORKSPACE.
Git plugin GIT_COMMIT, GIT_BRANCH after checkout.
environment block Values you define in the Jenkinsfile.
parameters Choices made when the build starts.
1 / 2

Built-in variables

Jenkins sets many variables for you in every build. The ones you will use most:

Variable Meaning
BUILD_NUMBER The build's sequence number, such as 42
BUILD_ID Same as the number in current versions
BUILD_URL Full URL of this build's page
JOB_NAME Name of the job, including folders, like team/app/main
WORKSPACE Absolute path of the workspace on the agent
NODE_NAME Name of the agent running the build
JENKINS_URL Base URL of the Jenkins server
BRANCH_NAME Branch (or PR-12) in multibranch jobs
CHANGE_ID Pull request number, only in pull request builds
GIT_COMMIT Full commit hash, set after the Git checkout
GIT_BRANCH Branch name the Git plugin checked out

The exact set depends on your plugins and job type; a variable that does not apply (like CHANGE_ID on a normal branch build) is simply missing. The full list for your server is shown on the page at JENKINS_URL/pipeline-syntax/globals#env.

Read them in a shell step as ordinary variables, and in Groovy through the env object:

GROOVY
steps {
  sh 'echo "Build $BUILD_NUMBER of $JOB_NAME"'
  echo "Commit is ${env.GIT_COMMIT}"
}

The environment block

Define your own variables once and use them in every step:

GROOVY
pipeline {
  agent any
  environment {
    APP_NAME   = 'shop'
    IMAGE_TAG  = "build-${env.BUILD_NUMBER}"
    DEPLOY_ENV = 'staging'
  }
  stages {
    stage('Build') {
      environment {
        DEPLOY_ENV = 'ci'   // overrides only inside this stage
      }
      steps {
        sh 'echo "$APP_NAME:$IMAGE_TAG in $DEPLOY_ENV"'
      }
    }
    stage('Deploy') {
      steps {
        sh 'echo "Deploying to $DEPLOY_ENV"'
      }
    }
  }
}

The Build stage prints shop:build-42 in ci, and the Deploy stage prints staging, because a stage's own environment applies only to that stage. Values are strings. Double quotes (as in IMAGE_TAG) let Groovy interpolate other variables.

environment can also pull secrets with credentials('id'). Secret handling has its own rules; see Credentials and Secrets.

Parameters

parameters declares inputs that appear on the Build with Parameters page. Jenkins builds that form from the declaration.

GROOVY
pipeline {
  agent any
  parameters {
    string(name: 'TARGET', defaultValue: 'staging', description: 'Where to deploy')
    choice(name: 'LOG_LEVEL', choices: ['info', 'debug', 'warn'], description: 'Verbosity')
    booleanParam(name: 'RUN_SLOW_TESTS', defaultValue: false, description: 'Include the slow suite')
  }
  stages {
    stage('Test') {
      steps {
        sh 'make test'
      }
    }
    stage('Slow tests') {
      when { expression { params.RUN_SLOW_TESTS } }
      steps {
        sh 'make test-slow'
      }
    }
    stage('Deploy') {
      steps {
        echo "Deploying to ${params.TARGET} with log level ${params.LOG_LEVEL}"
      }
    }
  }
}

The choice parameter takes a list; the first item is the default. Read values with params.NAME. Other types exist: text (multi-line), password and file.

Things that surprise people

  1. The first run. Jenkins learns about parameters by running the pipeline. After you add one to the Jenkinsfile, the first build uses default values (and a build triggered by a webhook always uses defaults); the "Build with Parameters" form shows the new fields afterwards.
  2. Types differ by access. In params, a booleanParam is a real boolean. As an environment variable ($RUN_SLOW_TESTS in a shell) it is the string "true" or "false". In Groovy, the string "false" is truthy if you test it directly, which is a classic bug. Use params.RUN_SLOW_TESTS in Groovy conditions, and compare with == 'true' for the env version.
  3. Triggered builds. Builds started by a timer, a webhook or SCM polling get defaults, because no person filled in a form. Choose defaults that are safe, such as staging and not production.

withEnv

withEnv sets variables for the steps inside one block:

GROOVY
steps {
  withEnv(['LOG_LEVEL=debug', "RELEASE=${env.BUILD_NUMBER}"]) {
    sh 'echo "level=$LOG_LEVEL release=$RELEASE"'
  }
  sh 'echo "outside: ${LOG_LEVEL:-not set}"'
}

After the closing brace, the variables are gone. It is the right tool when only a few steps need a different value, and it works in scripted pipelines as well.

Which value wins?

Several places can define the same name. Think of them as layers, from the outside in:

  1. The agent's own environment (what the operating system and Jenkins start the build with).
  2. Jenkins build variables: the built-ins and your parameters.
  3. The pipeline-level environment block.
  4. A stage-level environment block.
  5. withEnv around the steps.

The innermost layer wins while you are inside it, and the outer value returns afterwards. Two practical consequences: do not give an environment variable the same name as a parameter, because it is confusing which one a shell step will see, and do not reuse built-in names. Pick a clear prefix such as APP_ for your own variables.

The stand-in below models these layers. It resolves a variable by walking the layers from the innermost to the outermost, and it applies parameter defaults and the boolean-as-string rule.

JS Resolving variables through layers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The most important line is the clash: LOG_LEVEL is declared both as a parameter (debug) and in the pipeline environment (warn), and the model lets the environment layer win, so a shell step sees warn even though the person chose debug. In real Jenkins the details of this overlap are subtle enough that the safe rule is simply: never use the same name twice. The last three lines show the boolean surprise.

Reading variables safely in a script

When a value might be missing, give a fallback instead of letting the pipeline fail halfway:

JS Reading values with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Branch names contain slashes that are not allowed in Docker image tags, so the model replaces anything unusual with a dash. You will meet the same cleanup in Docker Agents and Building Images.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A stage-level environment block sets DEPLOY_ENV = 'ci' and the pipeline-level block sets 'staging'. What does a step in that stage see?

    The innermost definition wins while you are inside that stage, and the outer value is back after it.
  2. 2. Why do webhook-triggered builds often ignore the choices on the Build with Parameters page?

    Automatic triggers have nobody to supply values, so every parameter takes its declared default.
  3. 3. Which is the right way to test a boolean parameter in Groovy?

    params gives a real boolean. The env value is the string 'true' or 'false', and the string 'false' is truthy.
  4. 4. What is the default of a choice parameter?

    Jenkins preselects the first choice, so put the safest value first.
  5. 5. Which variable is only present in pull request builds of a multibranch job?

    CHANGE_ID holds the pull request number and is absent from ordinary branch builds.

Summary

  • Jenkins provides built-in variables such as BUILD_NUMBER, JOB_NAME, WORKSPACE and (after checkout) GIT_COMMIT.
  • environment defines your own variables at pipeline or stage level; withEnv does so for one block.
  • parameters create the Build with Parameters form; read them with params.NAME.
  • Automatic triggers use parameter defaults, so make defaults safe.
  • Booleans are real in params but strings in the environment.
  • The innermost layer wins; avoid reusing names across layers.

Next, make stages run only when they should, and clean up afterwards, in Conditions and Post Actions.