Jenkins Pipeline
A comprehensive developer cheatsheet covering Jenkins Pipeline as Code, featuring essential Groovy syntax, Declarative and Scripted workflows, key directives, common build steps, and operational best practices.
What is Jenkins Pipeline?
Jenkins Pipeline is a suite of plugins that supports implementing and integrating continuous delivery pipelines into Jenkins. It is defined as code (Jenkinsfile).
Why Pipeline as Code?
| Benefit | Description |
|---|---|
| Version Control | Pipeline is stored in SCM |
| Review | Changes can be peer-reviewed |
| Reusable | Shared libraries for common patterns |
| Durable | Survives Jenkins restarts |
| Visual | Blue Ocean UI for visualization |
Pipeline Types
Comparison
| Feature | Declarative Pipeline | Scripted Pipeline |
|---|---|---|
| Syntax | Simplified, structured | Flexible, Groovy-based |
| Learning Curve | Easy | Steeper |
| Structure | Pre-defined sections | Free-form Groovy |
| Error Handling | Built-in | Manual (try/catch) |
| Visualization | Better | Good |
| When to Use | Most use cases | Complex logic |
Basic Structure Comparison
Declarative:
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
}Scripted:
node {
stage('Build') {
echo 'Building...'
}
}Declarative Pipeline
Basic Syntax
pipeline {
agent any
stages {
stage('Stage Name') {
steps {
// Commands to run
}
}
}
}Complete Example
pipeline {
// Agent configuration
agent {
label 'linux'
}
// Build parameters
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'])
booleanParam(name: 'RUN_TESTS', defaultValue: true)
}
// Environment variables
environment {
NODE_ENV = 'production'
APP_VERSION = '1.0.${BUILD_NUMBER}'
}
// Tools (JDK, Maven, etc.)
tools {
maven 'maven-3'
jdk 'jdk-11'
}
// Build triggers
triggers {
cron('H 2 * * *')
pollSCM('H/5 * * * *')
githubPush()
}
// Options
options {
timestamps()
timeout(time: 1, unit: 'HOURS')
buildDiscarder(logRotator(numToKeepStr: '10'))
skipStagesAfterUnstable()
}
// Stages
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'mvn clean compile'
}
post {
failure {
echo 'Build failed!'
}
}
}
stage('Test') {
when {
expression { params.RUN_TESTS == true }
}
steps {
sh 'mvn test'
}
post {
always {
junit '**/target/surefire-reports/*.xml'
}
}
}
stage('Deploy') {
when {
expression { params.ENVIRONMENT == 'production' }
}
steps {
sh 'mvn deploy -P production'
}
}
}
// Post-build actions
post {
success {
echo 'Pipeline succeeded!'
emailext(
subject: "Build ${env.BUILD_NUMBER} succeeded",
body: "See: ${env.BUILD_URL}",
to: 'team@example.com'
)
}
failure {
echo 'Pipeline failed!'
emailext(
subject: "Build ${env.BUILD_NUMBER} failed",
body: "See: ${env.BUILD_URL}",
to: 'team@example.com'
)
}
always {
cleanWs()
}
}
}Key Directives
| Directive | Purpose | Example |
|---|---|---|
agent | Where to run | agent any, agent { label 'linux' } |
stages | Pipeline stages | stage('Build') |
steps | Commands to run | sh 'echo Hello' |
environment | Environment variables | NODE_ENV = 'prod' |
parameters | Build parameters | string(name: 'BRANCH') |
triggers | Build triggers | cron('H 2 * * *') |
tools | Tools to use | maven 'maven-3' |
when | Conditional execution | when { branch 'main' } |
post | Post-build actions | success { }, failure { } |
options | Build options | timestamps() |
Scripted Pipeline
Basic Syntax
node {
stage('Stage Name') {
sh 'echo Hello'
}
}Complete Example
// Define variables
def APP_VERSION = '1.0'
def BRANCH = env.BRANCH_NAME ?: 'main'
// Node block
node('linux') {
// Checkout
stage('Checkout') {
checkout scm
}
// Build
stage('Build') {
try {
sh 'mvn clean compile'
} catch (Exception e) {
currentBuild.result = 'FAILURE'
throw e
}
}
// Test
stage('Test') {
try {
sh 'mvn test'
} finally {
junit '**/target/surefire-reports/*.xml'
}
}
// Deploy (conditional)
stage('Deploy') {
if (BRANCH == 'main') {
sh 'mvn deploy'
} else {
echo "Skipping deploy for branch: ${BRANCH}"
}
}
// Post-build
stage('Post-build') {
script {
if (currentBuild.result == 'SUCCESS') {
emailext(
subject: "Build ${env.BUILD_NUMBER} succeeded",
body: "See: ${env.BUILD_URL}",
to: 'team@example.com'
)
}
}
}
// Cleanup
stage('Cleanup') {
cleanWs()
}
}Key Concepts
| Concept | Purpose | Example |
|---|---|---|
node | Allocate executor | node('linux') |
stage | Stage block | stage('Build') |
sh | Shell command | sh 'ls -la' |
def | Define variable | def name = 'value' |
try/catch | Error handling | try { sh '...' } catch {} |
currentBuild | Build status | currentBuild.result = 'FAILURE' |
env | Environment vars | env.BUILD_NUMBER |
Common Pipeline Steps
SCM Steps
| Step | Purpose | Example |
|---|---|---|
checkout | Checkout SCM | checkout scm |
git | Git checkout | git url: 'https://github.com/...' |
withCredentials | Credentials | withCredentials([string(...)]) |
Shell & Script Steps
| Step | Purpose | Example |
|---|---|---|
sh | Execute shell | sh 'echo Hello' |
bat | Execute batch | bat 'echo Hello' |
powershell | Execute PowerShell | powershell 'Write-Host Hello' |
script | Groovy script | script { def x = 1 + 2 } |
Artifact Steps
| Step | Purpose | Example |
|---|---|---|
archiveArtifacts | Archive artifacts | archiveArtifacts '**/target/*.jar' |
stash | Stash files | stash name: 'files', includes: 'src/**' |
unstash | Unstash files | unstash name: 'files' |
copyArtifacts | Copy from other job | copyArtifacts projectName: 'job' |
Test & Reporting Steps
| Step | Purpose | Example |
|---|---|---|
junit | Publish JUnit test results | junit '**/test-results/*.xml' |
publishHTML | Publish HTML report | publishHTML([reportDir: 'reports']) |
recordIssues | Record issues | recordIssues(tools: [jdk(), maven()]) |
Docker Steps
| Step | Purpose | Example |
|---|---|---|
docker.build | Build Docker image | docker.build('myapp') |
docker.push | Push Docker image | docker.push('latest') |
docker.withRegistry | Use registry | docker.withRegistry('https://...') |
docker.image | Pull image | docker.image('nginx').run() |
Notification Steps
| Step | Purpose | Example |
|---|---|---|
emailext | Send email | emailext(to: 'team@example.com') |
slackSend | Send Slack | slackSend(message: 'Build complete') |
Cleanup Steps
| Step | Purpose | Example |
|---|---|---|
cleanWs | Clean workspace | cleanWs() |
deleteDir | Delete directory | deleteDir() |
Quick Reference — Most Used Commands
| Task | Command |
|---|---|
| Declarative pipeline template | pipeline { agent any; stages { stage('Build') { steps { echo '...' } } } } |
| Scripted pipeline template | node { stage('Build') { echo '...' } } |
| Run shell command | sh 'echo Hello' |
| Checkout Git | checkout scm |
| Archive artifacts | archiveArtifacts '**/target/*.jar' |
| Publish test results | junit '**/test-results/*.xml' |
| Conditional branch | when { branch 'main' } |
| Environment variable | environment { VAR = 'value' } |
| Parameter | parameters { string(name: 'BRANCH') } |
| Send email | emailext(to: 'team@example.com', subject: 'Build') |
| Clean workspace | cleanWs() |
Pro Tips
-
Use Declarative Pipeline for 90% of use cases.
-
Jenkinsfile should be in SCM root.
-
Use
whenfor conditional stages. -
Always archive artifacts for debugging.
-
Use
postfor cleanup (always, success, failure). -
Keep pipelines small — use Shared Libraries for reuse.
-
Environment variables are global.
-
Use
timestamps()option for better logs. -
Stash/unstash for sharing between stages.
-
Test pipeline changes with
Replaybefore committing.