Skip to main content

Jenkins Pipeline: Jenkinsfile Syntax, Stages & Shared Libraries

Jenkins Pipeline is the backbone of CI/CD in thousands of enterprises. Whether you are writing your first Jenkinsfile or migrating from Scripted to Declarative syntax, this guide covers everything from basic stage structure to advanced shared library patterns — with working code examples you can copy today.

✓ Declarative & Scripted Pipeline syntax ✓ Parallel stages & failFast ✓ Shared Libraries setup ✓ Post-build actions & notifications ✓ Jenkins vs GitHub Actions vs CircleCI
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →

Declarative Pipeline Structure

Declarative Pipeline is the recommended approach for most teams. The pipeline block enforces a clear structure: agent, environment, stages, and post. Jenkins validates the syntax before any agent is allocated, giving you faster feedback on configuration errors.

// Jenkinsfile (Declarative Pipeline)
pipeline {
  agent any

  environment {
    NODE_VERSION = '20'
    DEPLOY_ENV   = 'staging'
  }

  stages {
    stage('Install') {
      steps {
        sh 'npm ci'
      }
    }
    stage('Test') {
      steps {
        sh 'npm test -- --ci --coverage'
      }
      post {
        always {
          junit 'coverage/junit.xml'
        }
      }
    }
    stage('Build') {
      steps {
        sh 'npm run build'
        archiveArtifacts artifacts: 'dist/**', fingerprint: true
      }
    }
    stage('Deploy') {
      when {
        branch 'main'
      }
      steps {
        sh './scripts/deploy.sh ${DEPLOY_ENV}'
      }
    }
  }

  post {
    failure {
      slackSend(color: 'danger', message: "Build failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}")
    }
    always {
      cleanWs()
    }
  }
}

Parallel Stages

Running stages in parallel dramatically reduces total pipeline duration. Jenkins allocates separate executors for each parallel branch. Use failFast: true to cancel all other branches the moment one fails — essential for fast feedback in large test suites.

stage('Parallel Checks') {
  parallel {
    stage('Unit Tests') {
      steps { sh 'npm run test:unit' }
    }
    stage('Integration Tests') {
      steps { sh 'npm run test:integration' }
    }
    stage('Lint') {
      steps { sh 'npm run lint' }
    }
    stage('Security Scan') {
      steps { sh 'npm audit --audit-level=high' }
    }
  }
  // abort all branches when any one fails
  failFast true
}

Shared Libraries

Shared Libraries eliminate copy-paste across Jenkinsfiles. Define reusable steps in a dedicated Git repository under vars/ and import them with @Library. Configure the library URL in Jenkins → Manage Jenkins → Configure System → Global Pipeline Libraries.

// vars/deployApp.groovy  (in your shared library repo)
def call(String environment, String appName) {
  echo "Deploying ${appName} to ${environment}"
  sh "kubectl set image deployment/${appName} app=${appName}:${env.BUILD_NUMBER} -n ${environment}"
  sh "kubectl rollout status deployment/${appName} -n ${environment}"
}

// Jenkinsfile  (in your application repo)
@Library('my-shared-library') _

pipeline {
  agent any
  stages {
    stage('Deploy to Staging') {
      steps {
        deployApp('staging', 'my-api')
      }
    }
  }
}

Jenkins vs GitHub Actions vs CircleCI

Feature Jenkins GitHub Actions CircleCI
Infrastructure Self-hosted (required) Cloud or self-hosted Cloud or self-hosted
Config format Groovy DSL (Jenkinsfile) YAML (.github/workflows) YAML (.circleci/config.yml)
Free tier Free (self-host costs) Free public repos; 2,000 min/mo private 6,000 free credits/mo
Parallelism parallel block matrix strategy parallelism key (test splitting)
Reusable logic Shared Libraries Reusable Workflows / Actions Orbs
Best for Enterprise, on-prem, complex pipelines GitHub-hosted projects, open source Large test suites needing speed

Key Best Practices

  • ✓Pin agent images. Use agent { docker { image 'node:20-alpine' } } to ensure reproducible builds across all runs.
  • ✓Use credentials binding. Reference secrets via withCredentials([string(credentialsId: 'API_KEY', variable: 'KEY')]) — never hardcode secrets.
  • ✓Gate deploys with when conditions. Use when { branch 'main' } to prevent feature branches from deploying to production accidentally.
  • ✓Archive test reports. Use junit and publishHTML to make test results visible in the Jenkins UI without digging through logs.

Frequently Asked Questions

What is the difference between Declarative and Scripted Pipeline?▼

Declarative Pipeline is the modern recommended syntax — it uses a structured pipeline {} block with predefined sections (agent, stages, post) that enforce best practices and provide better error messages. Scripted Pipeline is Groovy-based (node {} block), giving you full programmatic control but requiring more Groovy knowledge. Use Declarative unless you need dynamic logic that Declarative cannot express.

How do I validate Jenkinsfile syntax without running the pipeline?▼

Use the Jenkins CLI: curl --user user:token -X POST -F 'jenkinsfile=<Jenkinsfile' https://jenkins.example.com/pipeline-model-converter/validate. Alternatively, use the Jenkins Replay feature to test modified scripts, or integrate the Jenkins Linter VS Code extension that validates syntax on save. The declarative linter catches syntax errors before any agents are allocated.

What are Jenkins Shared Libraries and when should I use them?▼

Shared Libraries let you define reusable Groovy functions and pipeline steps in a separate Git repository, then import them across all your Jenkinsfiles with @Library('my-lib'). Use them when multiple pipelines share the same build/deploy/notify logic — it eliminates copy-paste drift. Store the library at vars/ (global callable steps) and src/ (Groovy classes). Configure the library in Jenkins → Manage Jenkins → Configure System → Global Pipeline Libraries.

How do I run pipeline stages in parallel?▼

Use the parallel directive inside a stage: parallel { stage('Unit Tests') { steps { sh 'npm test' } } stage('Lint') { steps { sh 'npm run lint' } } }. Parallel stages run simultaneously on the same or different agents. Add failFast: true as a sibling to parallel to abort all branches immediately when one fails. Jenkins 2.x supports parallel stages natively in Declarative Pipeline.

How do I handle post-build actions like notifications and cleanup?▼

Use the post {} block at the pipeline or stage level. It supports always (always runs), success, failure, unstable, changed (status changed from previous run), and cleanup (runs after all other post conditions). Example: post { failure { slackSend(message: 'Build failed!') } always { cleanWs() } }. The always block is ideal for archiving artifacts and workspace cleanup regardless of outcome.

Jenkins vs GitHub Actions vs CircleCI — which should I pick?▼

Jenkins gives you maximum flexibility and is ideal for complex enterprise pipelines with on-prem requirements, but requires maintenance of the Jenkins server itself. GitHub Actions is the easiest path for GitHub-hosted repos — zero infrastructure, marketplace of 10,000+ actions, free for public repos. CircleCI excels at test parallelism and build speed with its orbs ecosystem. For new greenfield projects on GitHub, GitHub Actions is the default choice. Jenkins remains dominant in enterprises with existing infrastructure.