Declarative Pipeline Directives: environment, parameters, options, when, input, tools and Variables
Full Example First
groovy
pipeline {
agent any
options {
timeout(time: 30, unit: 'MINUTES')
timestamps()
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5'))
skipDefaultCheckout(false)
ansiColor('xterm')
}
parameters {
string(name: 'TARGET_ENV', defaultValue: 'staging', description: 'Where to deploy')
choice(name: 'LOG_LEVEL', choices: ['info', 'debug', 'warn'], description: 'Log level')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run the test stage')
password(name: 'DEPLOY_PASS', defaultValue: '', description: 'One time password')
}
environment {
APP_NAME = 'shop'
VERSION = "1.4.${env.BUILD_NUMBER}"
REGISTRY = 'registry.example.com'
DOCKER_CRED = credentials('docker-hub')
}
stages {
stage('Build') {
steps {
echo "Building ${APP_NAME} ${VERSION} for ${params.TARGET_ENV}"
sh 'echo $VERSION'
}
}
stage('Test') {
when { expression { params.RUN_TESTS } }
steps { sh 'make test' }
}
stage('Deploy to production') {
when {
allOf {
branch 'main'
environment name: 'DEPLOY_TO_PROD', value: 'true'
}
}
input {
message 'Deploy to production?'
ok 'Deploy'
submitter 'release-managers'
}
steps { sh './deploy.sh prod' }
}
}
}
environment
- Defines variables for all stages (top level) or one stage (inside the stage)
- Values can be plain text, Groovy strings with other variables, or
credentials('id') - Inside
sh, use$VERSION(shell) in single quotes; inside Groovy strings use${VERSION}in double quotes - A variable defined with
environmentcannot be changed later in the pipeline. For dynamic values usescript { env.X = '...' }
groovy
stage('Build') {
environment { MAVEN_OPTS = '-Xmx1g' } // only in this stage
steps {
script {
env.GIT_SHORT = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
}
sh 'echo built $GIT_SHORT'
}
}
Built-in Variables
| Variable | Meaning |
|---|---|
env.BUILD_NUMBER, env.BUILD_URL | This build |
env.JOB_NAME, env.WORKSPACE | Job and workspace path |
env.BRANCH_NAME | Branch (multibranch pipelines only) |
env.CHANGE_ID, env.CHANGE_TARGET | Pull request number and target branch (multibranch) |
env.TAG_NAME | Git tag being built (multibranch) |
env.GIT_COMMIT, env.GIT_URL | Set by the Git checkout |
currentBuild.result, currentBuild.durationString | Status and time of the running build |
params.NAME | Value of a parameter |
parameters
| Type | Example |
|---|---|
string | string(name: 'VERSION', defaultValue: '1.0', description: '...') |
text | Multi-line text |
booleanParam | booleanParam(name: 'DRY_RUN', defaultValue: false) |
choice | choice(name: 'ENV', choices: ['dev','staging','prod']) |
password | Masked value |
file | Uploaded file |
First run quirk: After you add
parameters to a Jenkinsfile, the first build runs with defaults because Jenkins learns the parameters only when it reads the file. From the second build the Build with Parameters form appears.
options
| Option | Effect |
|---|---|
timeout(time: 30, unit: 'MINUTES') | Abort if the pipeline runs too long |
retry(2) | Retry the whole pipeline on failure |
timestamps() | Add a time prefix to every log line |
disableConcurrentBuilds() | Never run two builds of this job at once |
buildDiscarder(logRotator(numToKeepStr: '20')) | Keep only the last 20 builds |
skipDefaultCheckout() | Do not check out automatically |
skipStagesAfterUnstable() | Stop running stages after the build becomes unstable |
preserveStashes() | Keep stashes for restarts |
parallelsAlwaysFailFast() | Abort other parallel branches on the first failure |
groovy
stage('Integration tests') {
options { timeout(time: 10, unit: 'MINUTES'); retry(2) } // stage-level options
steps { sh './integration.sh' }
}
when: Run a Stage Only If
| Condition | Meaning |
|---|---|
branch 'main' | Branch name matches (multibranch). Supports comparator: 'GLOB', e.g. branch pattern: 'release-*', comparator: 'GLOB' |
tag 'v*' | A Git tag that matches |
changeRequest() | Building a pull request |
environment name: 'X', value: 'y' | Environment variable equals a value |
expression { params.RUN_TESTS } | Any Groovy expression that returns true |
changeset 'src/**' | Files in this path changed |
triggeredBy 'TimerTrigger' | Build was started by a timer, user or SCM |
allOf { ... }, anyOf { ... }, not { ... } | Combine conditions |
groovy
stage('Deploy') {
when {
beforeAgent true // evaluate before allocating an agent: saves resources
anyOf {
branch 'main'
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
}
}
steps { sh './deploy.sh' }
}
input: Manual Approval
groovy
stage('Approve') {
steps {
timeout(time: 1, unit: 'DAYS') {
input message: 'Promote build to production?',
ok: 'Promote',
submitter: 'alice,bob,release-managers',
parameters: [choice(name: 'STRATEGY', choices: ['rolling', 'blue-green'], description: 'How to deploy')]
}
}
}
- The pipeline pauses and waits. Put
inputin a stage withagent noneor usebeforeAgentso it does not hold an executor while waiting - Always add a timeout so abandoned approvals do not stay forever
submitterlimits who can approve
tools and triggers
groovy
pipeline {
agent any
tools { maven 'maven-3.9'; jdk 'jdk21' }
triggers { cron('H 2 * * 1-5') }
stages { stage('Info') { steps { sh 'mvn -v' } } }
}
Groovy Strings: Single vs Double Quotes
| Code | Result |
|---|---|
echo 'v${VERSION}' | Prints the literal text v${VERSION}. No expansion |
echo "v${VERSION}" | Groovy replaces ${VERSION} before running |
sh 'echo $VERSION' | The shell expands $VERSION (from the environment) |
sh "echo ${params.TARGET}" | Groovy inserts the parameter value into the command first |
sh "echo \$HOME" | Escape $ so the shell sees it |
Practice Tasks
- Add parameters and options to your Jenkinsfile and use each value in a stage
- Create a stage that runs only on
mainand one that runs only for pull requests - Add a manual approval with a one-day timeout
- Use
when { changeset }to skip a stage when only docs changed - Explain the difference between
$VARand${VAR}inshwith single and double quotes
Conclusion
Directives shape pipeline behaviour: environment for variables and credentials, parameters for inputs, options for timeouts and build history, when for conditional stages, input for approvals and tools for build tools. Remember the Groovy quote rules and that parameters appear from the second run.
Quick Summary: environment/credentials(); built-in vars; parameters types; options; when conditions + beforeAgent; input + timeout; tools/triggers; quote rules.

