New batchZero to DevOps starts 29 Nov · limited seatsReserve your seat
Cheat sheetsJenkinsJenkins
FreeSheet 03 of 7

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?

BenefitDescription
Version ControlPipeline is stored in SCM
ReviewChanges can be peer-reviewed
ReusableShared libraries for common patterns
DurableSurvives Jenkins restarts
VisualBlue Ocean UI for visualization

Pipeline Types

Comparison

FeatureDeclarative PipelineScripted Pipeline
SyntaxSimplified, structuredFlexible, Groovy-based
Learning CurveEasySteeper
StructurePre-defined sectionsFree-form Groovy
Error HandlingBuilt-inManual (try/catch)
VisualizationBetterGood
When to UseMost use casesComplex logic

Basic Structure Comparison

Declarative:

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
}

Scripted:

groovy
node {
    stage('Build') {
        echo 'Building...'
    }
}

Declarative Pipeline

Basic Syntax

groovy
pipeline {
    agent any
    stages {
        stage('Stage Name') {
            steps {
                // Commands to run
            }
        }
    }
}

Complete Example

groovy
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

DirectivePurposeExample
agentWhere to runagent any, agent { label 'linux' }
stagesPipeline stagesstage('Build')
stepsCommands to runsh 'echo Hello'
environmentEnvironment variablesNODE_ENV = 'prod'
parametersBuild parametersstring(name: 'BRANCH')
triggersBuild triggerscron('H 2 * * *')
toolsTools to usemaven 'maven-3'
whenConditional executionwhen { branch 'main' }
postPost-build actionssuccess { }, failure { }
optionsBuild optionstimestamps()

Scripted Pipeline

Basic Syntax

groovy
node {
    stage('Stage Name') {
        sh 'echo Hello'
    }
}

Complete Example

groovy
// 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

ConceptPurposeExample
nodeAllocate executornode('linux')
stageStage blockstage('Build')
shShell commandsh 'ls -la'
defDefine variabledef name = 'value'
try/catchError handlingtry { sh '...' } catch {}
currentBuildBuild statuscurrentBuild.result = 'FAILURE'
envEnvironment varsenv.BUILD_NUMBER

Common Pipeline Steps

SCM Steps

StepPurposeExample
checkoutCheckout SCMcheckout scm
gitGit checkoutgit url: 'https://github.com/...'
withCredentialsCredentialswithCredentials([string(...)])

Shell & Script Steps

StepPurposeExample
shExecute shellsh 'echo Hello'
batExecute batchbat 'echo Hello'
powershellExecute PowerShellpowershell 'Write-Host Hello'
scriptGroovy scriptscript { def x = 1 + 2 }

Artifact Steps

StepPurposeExample
archiveArtifactsArchive artifactsarchiveArtifacts '**/target/*.jar'
stashStash filesstash name: 'files', includes: 'src/**'
unstashUnstash filesunstash name: 'files'
copyArtifactsCopy from other jobcopyArtifacts projectName: 'job'

Test & Reporting Steps

StepPurposeExample
junitPublish JUnit test resultsjunit '**/test-results/*.xml'
publishHTMLPublish HTML reportpublishHTML([reportDir: 'reports'])
recordIssuesRecord issuesrecordIssues(tools: [jdk(), maven()])

Docker Steps

StepPurposeExample
docker.buildBuild Docker imagedocker.build('myapp')
docker.pushPush Docker imagedocker.push('latest')
docker.withRegistryUse registrydocker.withRegistry('https://...')
docker.imagePull imagedocker.image('nginx').run()

Notification Steps

StepPurposeExample
emailextSend emailemailext(to: 'team@example.com')
slackSendSend SlackslackSend(message: 'Build complete')

Cleanup Steps

StepPurposeExample
cleanWsClean workspacecleanWs()
deleteDirDelete directorydeleteDir()

Quick Reference — Most Used Commands

TaskCommand
Declarative pipeline templatepipeline { agent any; stages { stage('Build') { steps { echo '...' } } } }
Scripted pipeline templatenode { stage('Build') { echo '...' } }
Run shell commandsh 'echo Hello'
Checkout Gitcheckout scm
Archive artifactsarchiveArtifacts '**/target/*.jar'
Publish test resultsjunit '**/test-results/*.xml'
Conditional branchwhen { branch 'main' }
Environment variableenvironment { VAR = 'value' }
Parameterparameters { string(name: 'BRANCH') }
Send emailemailext(to: 'team@example.com', subject: 'Build')
Clean workspacecleanWs()

Pro Tips

  1. Use Declarative Pipeline for 90% of use cases.

  2. Jenkinsfile should be in SCM root.

  3. Use when for conditional stages.

  4. Always archive artifacts for debugging.

  5. Use post for cleanup (always, success, failure).

  6. Keep pipelines small — use Shared Libraries for reuse.

  7. Environment variables are global.

  8. Use timestamps() option for better logs.

  9. Stash/unstash for sharing between stages.

  10. Test pipeline changes with Replay before committing.


Next in JenkinsJenkinsfile & Shared Libraries Pro