ENGIMY.IO - CHEATSHEET
JENKINS × CI/CD PIPELINES
REFERENCE vJenkins 2.x (Declarative Pipeline)

Jenkins Quick Reference

Automate build, test, and deploy – from simple CI to complex CD pipelines.

Installation & Setup

Run Jenkins Locally (Docker)
docker run -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts
Installation on Ubuntu
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update
sudo apt install jenkins
sudo systemctl start jenkins
sudo systemctl enable jenkins
Initial Setup
  • Access: http://localhost:8080
  • Initial admin password: sudo cat /var/lib/jenkins/secrets/initialAdminPassword
  • Install suggested plugins or select custom.
  • Create first admin user.

Pipeline Types

Type Best For Syntax
DeclarativeSimple, structured pipelinesSimpler, opinionated, with built-in validation
ScriptedComplex, programmatic logicGroovy-based, more flexible, less strict

Declarative Pipeline – Basic Structure

pipeline {
    agent any

    tools {
        maven 'Maven-3.9'
        jdk 'JDK-17'
    }

    environment {
        APP_NAME = 'myapp'
        DEPLOY_ENV = 'staging'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build') {
            steps {
                sh 'mvn clean compile'
            }
        }

        stage('Test') {
            steps {
                sh 'mvn test'
            }
            post {
                always {
                    junit 'target/surefire-reports/*.xml'
                }
            }
        }

        stage('Package') {
            steps {
                sh 'mvn package'
            }
        }

        stage('Deploy') {
            steps {
                sh './deploy.sh'
            }
        }
    }

    post {
        success {
            echo 'Pipeline succeeded!'
        }
        failure {
            echo 'Pipeline failed!'
            mail to: 'team@example.com', subject: 'Build failed'
        }
    }
}

Agents

// any available agent
agent any

// specific label
agent { label 'linux-agent' }

// Docker agent
agent {
    docker {
        image 'maven:3.9-eclipse-temurin-17'
        args '-v /var/run/docker.sock:/var/run/docker.sock'
    }
}

// Dockerfile agent
agent {
    dockerfile {
        filename 'Dockerfile.build'
        dir 'build'
        additionalBuildArgs '--build-arg VERSION=1.0'
    }
}

// none – each stage declares its own agent
agent none

Stages and Steps

Common Steps
// Shell commands
sh 'echo "Hello, Jenkins!"'
sh "mvn clean install -DskipTests"

// With return value
def version = sh(script: 'git describe --tags', returnStdout: true).trim()

// With exit code
def rc = sh(script: 'make test', returnStatus: true)
if (rc != 0) {
    error "Tests failed"
}

// Batch (Windows)
bat 'dir'

// Checkout SCM
checkout scm

// Git directly
git branch: 'main', url: 'https://github.com/user/repo.git'

// Archive artifacts
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true

// Publish test results
junit 'target/surefire-reports/*.xml'

// Send email
mail to: 'dev@example.com', subject: 'Build Complete', body: 'Check logs'

// Slack notification
slackSend channel: '#ci-cd', color: 'good', message: 'Build succeeded'

// Timeout
timeout(time: 30, unit: 'MINUTES') {
    sh 'long_running_script.sh'
}

// Retry
retry(3) {
    sh 'flaky_command.sh'
}

// Sleep
sleep time: 10, unit: 'SECONDS'

Environment Variables

pipeline {
    agent any

    environment {
        // Static variables
        DB_HOST = 'localhost'
        DB_PORT = '5432'

        // Credentials (using Jenkins credential store)
        DB_PASSWORD = credentials('db-password')
        GITHUB_TOKEN = credentials('github-token')

        // Computed
        BUILD_TIMESTAMP = currentBuild.startTimeInMillis
    }

    stages {
        stage('Print Env') {
            steps {
                sh 'echo $DB_HOST'
                sh 'echo $BUILD_NUMBER'
                sh 'echo $JOB_NAME'
                sh 'echo $WORKSPACE'
            }
        }
    }
}
Built‑in Environment Variables
  • BUILD_NUMBER – current build number
  • JOB_NAME – job name
  • WORKSPACE – absolute path of workspace
  • JENKINS_URL – Jenkins server URL
  • BUILD_URL – URL of current build
  • GIT_COMMIT – commit hash (if Git SCM used)
  • GIT_BRANCH – branch name
  • CHANGE_ID – PR number (if PR job)

Credentials Management

// Username + password
withCredentials([usernamePassword(credentialsId: 'my-creds', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
    sh 'echo $USER | docker login -u $USER -p $PASS'
}

// SSH private key
withCredentials([sshUserPrivateKey(credentialsId: 'ssh-key', keyFileVariable: 'SSH_KEY')]) {
    sh 'ssh -i $SSH_KEY user@host "ls"'
}

// Secret text (API token)
withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {
    sh 'curl -H "Authorization: Bearer $TOKEN" https://api.example.com'
}

// Secret file
withCredentials([file(credentialsId: 'gcp-key', variable: 'GCP_KEY')]) {
    sh 'export GOOGLE_APPLICATION_CREDENTIALS=$GCP_KEY'
}

Conditionals and Control Flow

// When directive (stage-level)
stage('Deploy') {
    when {
        branch 'main'  // only on main branch
    }
    steps {
        sh './deploy.sh'
    }
}

stage('Deploy Staging') {
    when {
        expression { return env.GIT_BRANCH == 'develop' }
    }
    steps {
        sh './deploy-staging.sh'
    }
}

stage('Deploy Prod') {
    when {
        allOf {
            branch 'main'
            expression { return currentBuild.result == null || currentBuild.result == 'SUCCESS' }
        }
    }
    steps {
        sh './deploy-prod.sh'
    }
}

// Scripted block (for complex logic)
stage('Conditional Steps') {
    steps {
        script {
            if (env.GIT_BRANCH == 'main') {
                sh 'make deploy-prod'
            } else if (env.GIT_BRANCH == 'develop') {
                sh 'make deploy-staging'
            } else {
                echo 'Skipping deploy for branch: ' + env.GIT_BRANCH
            }
        }
    }
}

Parallel Execution

stage('Parallel Tests') {
    parallel {
        stage('Unit Tests') {
            steps {
                sh 'mvn test -Dtest=UnitTestSuite'
            }
        }
        stage('Integration Tests') {
            steps {
                sh 'mvn test -Dtest=IntegrationTestSuite'
            }
        }
        stage('E2E Tests') {
            steps {
                sh 'npm run test:e2e'
            }
        }
    }
}

// Dynamic parallel stages
stage('Build All Services') {
    steps {
        script {
            def services = ['auth', 'api', 'worker']
            def parallelStages = [:]
            services.each { svc ->
                parallelStages[svc] = {
                    sh "make build-$svc"
                }
            }
            parallel parallelStages
        }
    }
}

Post-Build Actions

pipeline {
    agent any
    stages { ... }
    post {
        always {
            echo 'This will always run'
            cleanWs()  // Clean workspace
        }
        success {
            echo 'Pipeline succeeded'
            archiveArtifacts 'target/*.jar'
        }
        failure {
            echo 'Pipeline failed'
            slackSend channel: '#alerts', color: 'danger', message: 'Build failed'
        }
        unstable {
            echo 'Pipeline is unstable (tests failed but build OK)'
        }
        changed {
            echo 'Pipeline status changed from previous build'
        }
        fixed {
            echo 'Pipeline was failing and is now fixed'
        }
        regression {
            echo 'Pipeline was successful and is now failing'
        }
        aborted {
            echo 'Pipeline was aborted by user'
        }
    }
}

Shared Libraries

Directory Structure
src/                    // Java/Groovy classes
vars/                   // Global variable files (e.g., deploy.groovy)
resources/              // Resources (config, templates)
Example vars/deploy.groovy
def call(String environment) {
    sh "echo Deploying to ${environment}"
    sh "./deploy-${environment}.sh"
}
Using Shared Library
@Library('my-shared-library') _

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                deploy('staging')  // from vars/deploy.groovy
            }
        }
    }
}
Loading Shared Library from Git
@Library('my-shared-library@main') _
@Library(value='my-shared-library', changelog=false) _
@Library('my-shared-library@feature/branch') _

Multibranch Pipelines

  • Creates a pipeline for each branch automatically.
  • Supports PR builds (GitHub, Bitbucket, GitLab).
  • Uses Jenkinsfile from each branch.
// Jenkinsfile (PR build)
pipeline {
    agent any
    stages {
        stage('PR Checks') {
            when { changeRequest() }
            steps {
                sh 'make check'
                sh 'make test'
            }
        }
        stage('Main Branch Deploy') {
            when { branch 'main' }
            steps {
                sh './deploy-prod.sh'
            }
        }
    }
}

Pipeline Syntax Snippets (Common Patterns)

Build and Push Docker Image
stage('Docker Build & Push') {
    steps {
        script {
            def image = docker.build("myapp:${env.BUILD_NUMBER}")
            docker.withRegistry('https://registry.hub.docker.com', 'docker-hub-cred') {
                image.push()
                image.push('latest')
            }
        }
    }
}
Run Kubernetes Deployment
stage('K8s Deploy') {
    steps {
        withKubeConfig([credentialsId: 'kubeconfig']) {
            sh 'kubectl set image deployment/myapp myapp=myapp:${BUILD_NUMBER}'
            sh 'kubectl rollout status deployment/myapp'
        }
    }
}
SonarQube Analysis
stage('SonarQube') {
    steps {
        withSonarQubeEnv('SonarQube') {
            sh 'mvn sonar:sonar'
        }
    }
}
stage('Quality Gate') {
    steps {
        timeout(time: 1, unit: 'HOURS') {
            waitForQualityGate abortPipeline: true
        }
    }
}

Plugins (Essential)

Plugin Purpose
PipelineCore pipeline plugin
Git / GitHubSCM integration
Docker PipelineDocker build, run, push
KubernetesDynamic agents on K8s
SonarQube ScannerCode quality analysis
Slack / TeamsNotifications
Blue OceanModern UI
Pipeline Utility StepsExtra steps (readJSON, writeYAML, etc.)
Credentials BindingSecure credential usage

Best Practices

  • Store Jenkinsfile in SCM – version control your pipelines.
  • Use Declarative Pipeline – simpler, more readable, built-in validation.
  • Use shared libraries – DRY for common code across repos.
  • Keep stages small and focused – each stage should do one thing.
  • Use credentials binding – never hard-code secrets.
  • Enable timestamps – for better log readability.
  • Use post for cleanup – always clean workspace (cleanWs()).
  • Set up notifications – Slack/email for failure alerts.
  • Use when directives – for branch/PR conditional logic.
  • Use options for pipeline settings – timeout, retry, buildDiscarder.
  • Run builds in containers – for reproducible, isolated builds.
  • Monitor Jenkins health – disk space, plugin updates, executors.

Troubleshooting

  • Replay – modify and replay a pipeline run without committing.
  • Pipeline Syntax – built-in snippet generator (click "Pipeline Syntax" in job UI).
  • Logs – check console output, Jenkins system log (/var/log/jenkins/jenkins.log).
  • Declarative Validator – use pipeline { /* ... */ } with --dry-run.
  • Common errors – missing plugins, agent offline, credential permissions, script approval.
// Debugging with echo
stage('Debug') {
    steps {
        script {
            echo "Current branch: ${env.BRANCH_NAME}"
            echo "Build number: ${env.BUILD_NUMBER}"
            echo "Workspace: ${env.WORKSPACE}"
            sh 'pwd && ls -la'
        }
    }
}
📌 Quick Reference
Pipeline: Declarative (structure) vs Scripted (flexible)
Keywords: pipeline, agent, stages, steps, environment, when, post
Credentials: withCredentials (usernamePassword, sshUserPrivateKey, string, file)
Parallel: parallel { stage('A') { ... } stage('B') { ... } }
Common steps: sh, bat, checkout, archiveArtifacts, junit, mail, timeout, retry
Shared libraries: vars/ (global variables) + src/ (classes)
Debug: Replay, Pipeline Syntax generator, echo, console logs
← Back to All Cheatsheets