Environment, parameters & when

Configure and branch a pipeline.

Beginner12 min · lesson 7 of 15

Real pipelines need configuration, and the environment block is where it lives — key/value pairs available to every stage as environment variables. Define them once at the top (a version, a registry, a service name) and reference them throughout, so there is a single place to change and nothing is hardcoded three times in three stages.

Jenkinsfile
pipeline {
agent any
environment {
REGISTRY = 'registry.acme.internal'
IMAGE = "${REGISTRY}/payments-api"
VERSION = "1.4.${BUILD_NUMBER}" // Jenkins provides BUILD_NUMBER
}
stages {
stage('Build') { steps { sh 'docker build -t $IMAGE:$VERSION .' } }
}
}

Parameters: pipelines you can drive

Parameters let a human (or another job) supply values when the pipeline starts — a target environment, a boolean "run the slow tests", a version to deploy. They turn one pipeline into a small tool: the same Jenkinsfile handles staging and production because the environment is a choice at run time, not a copy-pasted second job.

Jenkinsfile
parameters {
choice(name: 'TARGET', choices: ['staging', 'production'], description: 'Deploy to')
booleanParam(name: 'RUN_E2E', defaultValue: false)
}
// referenced as params.TARGET and params.RUN_E2E in stages

when: run a stage only sometimes

The when directive gates a stage on a condition — deploy only on the main branch, run end-to-end tests only when the parameter is set, skip a stage for pull requests. It keeps one pipeline handling many situations instead of branching into separate jobs, and it makes the rules explicit and reviewable in the Jenkinsfile.

Jenkinsfile
stage('Deploy') {
when {
branch 'main' // only on main
expression { params.TARGET == 'production' }
}
steps { sh './deploy.sh $TARGET' }
}
Never put secrets in environment{}
The environment block is plain text in the Jenkinsfile, which lives in your repo — so a password or token placed there is committed to version control for everyone to read. Secrets come from the credentials store via withCredentials or credentials(), covered in the credentials lesson; environment is for non-sensitive config only.