📖 Guide

Jenkins Cheat Sheet — Complete Pipeline Reference

Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns. Searchable and organized.

137 commands across 12 categories

Pipeline Basics

CommandDescription
pipeline { }
Top-level block for a Declarative Pipeline
agent any
Run pipeline on any available agent
agent none
No global agent — must define per stage
agent { label 'linux' }
Run on an agent with a specific label
agent { node { label 'gpu' } }
Run on a node matching a label expression
stages { }
Container for all stage blocks
stage('Build') { steps { } }
Define a named stage with steps
steps { }
Container for the actual build steps within a stage
post { always { } }
Post-build actions block
post { success { } }
Run steps only on successful build
post { failure { } }
Run steps only on failed build
post { unstable { } }
Run steps when build is unstable
post { cleanup { } }
Run cleanup steps regardless of status (after all other post)
post { changed { } }
Run when build status differs from previous build

Declarative Pipeline

CommandDescription
environment { MY_VAR = 'value' }
Set environment variables for the pipeline or stage
environment { SECRET = credentials('secret-id') }
Inject credentials as environment variables
parameters { string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build') }
Define a string parameter
parameters { booleanParam(name: 'DEPLOY', defaultValue: false, description: 'Deploy after build') }
Define a boolean parameter
parameters { choice(name: 'ENV', choices: ['dev', 'staging', 'prod'], description: 'Target environment') }
Define a choice parameter
triggers { cron('H/15 * * * *') }
Trigger pipeline on a cron schedule
triggers { pollSCM('H/5 * * * *') }
Poll SCM for changes on schedule
triggers { upstream(upstreamProjects: 'job1,job2', threshold: hudson.model.Result.SUCCESS) }
Trigger when upstream jobs complete
options { timeout(time: 30, unit: 'MINUTES') }
Set pipeline timeout
options { retry(3) }
Retry the entire pipeline up to 3 times
options { timestamps() }
Prepend timestamps to console output
options { disableConcurrentBuilds() }
Prevent concurrent builds of this pipeline
options { buildDiscarder(logRotator(numToKeepStr: '10')) }
Keep only the last 10 builds
options { skipDefaultCheckout() }
Skip automatic SCM checkout
when { branch 'main' }
Execute stage only on a specific branch
when { environment name: 'ENV', value: 'prod' }
Execute stage only when env var matches
when { expression { return params.DEPLOY == true } }
Execute stage based on a Groovy expression
when { allOf { branch 'main' environment name: 'DEPLOY', value: 'true' } }
Execute stage when all conditions are met
when { anyOf { branch 'main' branch 'develop' } }
Execute stage when any condition is met
when { not { branch 'main' } }
Execute stage when condition is NOT met
when { changeset '**/*.js' }
Execute stage only if specific files changed
when { beforeAgent true branch 'main' }
Evaluate when before allocating an agent

Scripted Pipeline

CommandDescription
node { }
Allocate a node (executor) for scripted pipeline
node('linux') { }
Allocate a node with a specific label
stage('Build') { }
Define a stage in scripted pipeline
try { // steps } catch (err) { echo "Error: ${err}" throw err }
Error handling with try/catch
try { // steps } catch (err) { currentBuild.result = 'FAILURE' } finally { // cleanup }
Try/catch/finally pattern
timeout(time: 10, unit: 'MINUTES') { // steps }
Wrap steps with a timeout
retry(3) { // steps }
Retry steps up to 3 times
waitUntil { // return true when ready }
Wait until a condition is true
lock('my-resource') { // steps }
Lock a resource (requires Lockable Resources plugin)

Common Steps

CommandDescription
sh 'make build'
Execute a shell command (Linux/macOS)
sh ''' echo "multi-line" make build '''
Multi-line shell script
sh(script: 'command', returnStdout: true).trim()
Capture shell command output
sh(script: 'command', returnStatus: true)
Capture shell command exit code
bat 'dir'
Execute a batch command (Windows)
powershell 'Get-Process'
Execute a PowerShell command (Windows)
echo 'Hello World'
Print a message to console output
checkout scm
Checkout source code from configured SCM
git url: 'https://github.com/user/repo.git', branch: 'main'
Checkout a specific Git repository
git url: 'https://github.com/user/repo.git', credentialsId: 'github-creds'
Checkout with credentials
dir('subdir') { sh 'make' }
Change working directory for enclosed steps
writeFile file: 'output.txt', text: 'content'
Write text to a file
readFile file: 'config.json'
Read file contents as string
fileExists 'path/to/file'
Check if a file exists (returns boolean)
archiveArtifacts artifacts: '**/*.jar', fingerprint: true
Archive build artifacts
archiveArtifacts artifacts: 'dist/**', allowEmptyArchive: true
Archive artifacts (allow empty)
junit 'target/surefire-reports/*.xml'
Publish JUnit test results
junit testResults: '**/test-results/*.xml', allowEmptyResults: true
Publish JUnit results (allow empty)
stash name: 'build', includes: 'dist/**'
Stash files for use in another stage/node
unstash 'build'
Restore stashed files
input message: 'Deploy to production?', ok: 'Deploy'
Pause for manual approval
input message: 'Choose env', parameters: [choice(name: 'ENV', choices: ['staging', 'prod'])]
Manual input with parameters
sleep time: 30, unit: 'SECONDS'
Pause pipeline for a duration
error 'Build failed!'
Fail the build with a message
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { sh 'might-fail' }
Catch error without failing the entire build

Credentials & Secrets

CommandDescription
withCredentials([usernamePassword(credentialsId: 'my-creds', usernameVariable: 'USER', passwordVariable: 'PASS')]) { sh 'curl -u $USER:$PASS ...' }
Inject username/password credentials
withCredentials([string(credentialsId: 'api-key', variable: 'API_KEY')]) { sh 'curl -H "Authorization: Bearer $API_KEY" ...' }
Inject a secret text credential
withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) { sh 'kubectl get pods' }
Inject a secret file credential
withCredentials([sshUserPrivateKey(credentialsId: 'ssh-key', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) { sh 'ssh -i $SSH_KEY $SSH_USER@host' }
Inject SSH key credentials
environment { DOCKER_CREDS = credentials('docker-hub') }
Bind credentials in environment block (creates _USR and _PSW vars)

Parallel Execution

CommandDescription
parallel { stage('Unit Tests') { steps { sh 'make test-unit' } } stage('Integration Tests') { steps { sh 'make test-integration' } } }
Run stages in parallel (Declarative)
parallel( 'unit': { sh 'make test-unit' }, 'integration': { sh 'make test-integration' } )
Run steps in parallel (Scripted)
parallel failFast: true, ...
Fail immediately if any parallel branch fails
stage('Tests') { failFast true parallel { ... } }
Parallel with failFast in Declarative
def branches = [:] items.each { item -> branches[item] = { sh "test ${item}" } } parallel branches
Dynamic parallel execution from a list

Shared Libraries

CommandDescription
@Library('my-shared-lib') _
Load a shared library at the top of Jenkinsfile
@Library('my-shared-lib@main') _
Load a specific version/branch of shared library
library 'my-shared-lib'
Dynamically load a shared library
// vars/myStep.groovy def call(String name) { echo "Hello ${name}" }
Define a global variable/step in shared library
// src/org/example/Utils.groovy package org.example class Utils { ... }
Define a class in shared library src/
// Jenkinsfile myStep('World')
Call a shared library step

Jenkins CLI

CommandDescription
java -jar jenkins-cli.jar -s http://localhost:8080/ -auth user:token help
Show CLI help
java -jar jenkins-cli.jar -s <url> -auth user:token build <job>
Trigger a job build
java -jar jenkins-cli.jar -s <url> -auth user:token build <job> -p PARAM=value
Trigger a parameterized build
java -jar jenkins-cli.jar -s <url> -auth user:token list-jobs
List all jobs
java -jar jenkins-cli.jar -s <url> -auth user:token get-job <job>
Get job configuration XML
java -jar jenkins-cli.jar -s <url> -auth user:token console <job> <build>
Get console output of a build
java -jar jenkins-cli.jar -s <url> -auth user:token install-plugin <plugin>
Install a plugin
java -jar jenkins-cli.jar -s <url> -auth user:token safe-restart
Safely restart Jenkins
java -jar jenkins-cli.jar -s <url> -auth user:token groovy = < script.groovy
Execute a Groovy script on the controller
curl -X POST http://localhost:8080/job/<job>/build --user user:token
Trigger build via REST API
curl http://localhost:8080/job/<job>/lastBuild/api/json --user user:token
Get last build info via REST API

Docker Integration

CommandDescription
agent { docker { image 'node:18' } }
Run pipeline inside a Docker container
agent { docker { image 'maven:3.9' args '-v /tmp:/tmp' } }
Docker agent with volume mount
agent { docker { image 'my-app' registryUrl 'https://registry.example.com' registryCredentialsId 'docker-creds' } }
Docker agent from private registry
agent { dockerfile { filename 'Dockerfile.ci' dir 'docker' } }
Build agent from a Dockerfile
docker.build('my-image:${BUILD_NUMBER}')
Build a Docker image (Scripted)
docker.image('my-image').push('latest')
Push a Docker image (Scripted)
docker.image('node:18').inside { sh 'npm test' }
Run steps inside a Docker container (Scripted)
docker.withRegistry('https://registry.example.com', 'docker-creds') { docker.image('my-image').push() }
Push to a private registry (Scripted)

Notifications

CommandDescription
emailext subject: 'Build ${currentBuild.result}', body: 'Check ${BUILD_URL}', to: 'team@example.com'
Send email notification (Email Extension plugin)
emailext subject: '...', body: '...', recipientProviders: [developers(), requestor()]
Email to developers who made changes
slackSend channel: '#builds', message: "Build ${currentBuild.result}: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
Send Slack notification
slackSend color: 'danger', message: 'Build failed!'
Send colored Slack notification
office365ConnectorSend webhookUrl: '<url>', message: 'Build complete', status: currentBuild.result
Send Microsoft Teams notification
httpRequest url: '<webhook-url>', httpMode: 'POST', contentType: 'APPLICATION_JSON', requestBody: '{"text":"Build done"}'
Send webhook notification (HTTP Request plugin)

Common Patterns

CommandDescription
currentBuild.result
Get current build result (SUCCESS, FAILURE, UNSTABLE, null)
currentBuild.displayName = "#${BUILD_NUMBER} - ${params.ENV}"
Set custom build display name
currentBuild.description = 'Deployed to production'
Set build description
def version = sh(script: 'cat VERSION', returnStdout: true).trim()
Capture command output into a variable
def config = readJSON file: 'config.json'
Read and parse a JSON file (Pipeline Utility Steps plugin)
def props = readProperties file: 'gradle.properties'
Read a properties file
writeJSON file: 'output.json', json: data
Write data as JSON file
wrap([$class: 'BuildUser']) { echo "Started by: ${BUILD_USER}" }
Get the user who triggered the build
cleanWs()
Clean workspace (Workspace Cleanup plugin)
milestone()
Cancel older builds that haven't reached this point
properties([ pipelineTriggers([cron('H 2 * * *')]) ])
Set job properties programmatically

Environment Variables

CommandDescription
env.BUILD_NUMBER
Current build number
env.BUILD_URL
URL of the current build
env.JOB_NAME
Name of the job
env.JOB_URL
URL of the job
env.WORKSPACE
Absolute path to the workspace
env.NODE_NAME
Name of the agent running the build
env.BRANCH_NAME
Branch name (multibranch pipelines)
env.CHANGE_ID
Pull request ID (multibranch pipelines)
env.CHANGE_AUTHOR
Pull request author (multibranch pipelines)
env.GIT_COMMIT
Current Git commit hash
env.GIT_BRANCH
Current Git branch
env.JENKINS_URL
URL of the Jenkins instance
env.BUILD_TAG
Unique tag: jenkins-<job>-<number>
env.EXECUTOR_NUMBER
Executor number on the agent
env.MY_VAR = 'value'
Set a custom environment variable in Scripted Pipeline

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
🐹
Go Reference
Complete Go (Golang) reference — syntax, types, functions, concurrency, error handling, and common patterns.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.

📖 Free, searchable command reference. Bookmark this page for quick access.