Declarative Pipeline Directives: environment, parameters, options, when, input, tools and Variables

CI CD Pipelines with Jenkins 40 min min read Updated: Nov 17, 2026 Intermediate
Declarative Pipeline Directives: environment, parameters, options, when, input, tools and Variables
Intermediate Topic 2 of 5

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 environment cannot be changed later in the pipeline. For dynamic values use script { 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

VariableMeaning
env.BUILD_NUMBER, env.BUILD_URLThis build
env.JOB_NAME, env.WORKSPACEJob and workspace path
env.BRANCH_NAMEBranch (multibranch pipelines only)
env.CHANGE_ID, env.CHANGE_TARGETPull request number and target branch (multibranch)
env.TAG_NAMEGit tag being built (multibranch)
env.GIT_COMMIT, env.GIT_URLSet by the Git checkout
currentBuild.result, currentBuild.durationStringStatus and time of the running build
params.NAMEValue of a parameter

parameters

TypeExample
stringstring(name: 'VERSION', defaultValue: '1.0', description: '...')
textMulti-line text
booleanParambooleanParam(name: 'DRY_RUN', defaultValue: false)
choicechoice(name: 'ENV', choices: ['dev','staging','prod'])
passwordMasked value
fileUploaded 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

OptionEffect
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

ConditionMeaning
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 input in a stage with agent none or use beforeAgent so it does not hold an executor while waiting
  • Always add a timeout so abandoned approvals do not stay forever
  • submitter limits 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

CodeResult
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

  1. Add parameters and options to your Jenkinsfile and use each value in a stage
  2. Create a stage that runs only on main and one that runs only for pull requests
  3. Add a manual approval with a one-day timeout
  4. Use when { changeset } to skip a stage when only docs changed
  5. Explain the difference between $VAR and ${VAR} in sh with 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators