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.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
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
junitandpublishHTMLto 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.