Home DevOps Jenkins Pipeline Basics: Write Production-Grade CI/CD That Won't Burn You at 3 AM
Intermediate ✅ Tested on Jenkins 2.440+ | Pipeline Plugin 1.0+ 8 min · June 21, 2026

Jenkins Pipeline Basics: Write Production-Grade CI/CD That Won't Burn You at 3 AM

Learn Jenkins Pipeline from scratch with production-grade practices.

N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Everything here is grounded in real deployments.

Follow
Production
production tested
July 15, 2026
last updated
2,406
articles · all by Naren
Before you start⏱ 25 min
  • Solid grasp of DevOps fundamentals
  • Comfortable with command-line tools
  • Basic Linux administration knowledge
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Use Declarative Pipeline for readability; Scripted only when needed for complex logic.
  • Always wrap risky stages in try-catch or post failure blocks to handle failures gracefully.
  • Store credentials in Jenkins Credentials Store, never hardcode.
  • Use shared libraries to reuse pipeline code across repos.
  • Enable pipeline durability (Pipeline: Stage View with persistence) to survive restarts.
  • Set up notifications (email, Slack) for pipeline failures and recovery.
  • Use agent none at top and assign agents per stage to optimize resource usage.
  • Version control your Jenkinsfile alongside your application code.
✦ Definition~90s read
What is Jenkins Pipeline Basics?

Jenkins Pipeline is a suite of plugins that lets you define your entire CI/CD process as code in a Jenkinsfile. It supports two syntaxes: Declarative (structured, easier) and Scripted (flexible, Groovy-based). Pipelines survive Jenkins restarts and can be version-controlled.

Think of Jenkins Pipeline as a GPS for your software delivery.

In production, the pipeline is the backbone of your delivery. It must handle flaky tests, network timeouts, credential rotation, and infrastructure failures. A solid pipeline uses declarative syntax for its readability and built-in error handling, resorts to scripted blocks only for complex logic, and leverages shared libraries for reuse across teams.

Production-grade pipelines also integrate with external systems: artifact repositories (Nexus, Artifactory), container registries (Docker Hub, ECR), deployment tools (Kubernetes, Ansible), and notification services (Slack, PagerDuty). They are designed to be idempotent and to fail fast with clear messages.

Plain-English First

Think of Jenkins Pipeline as a GPS for your software delivery. You tell it the start (code commit) and destination (production), and it gives turn-by-turn directions: 'Run tests, build, deploy.' But unlike a GPS, if you hit a roadblock (test fails), Jenkins stops and sends you an alert. Over time, you can teach it shortcuts (parallel stages) and detours (error handling) so it never gets stuck at 3 AM.

A production-grade pipeline is like a self-driving car with a mechanic. It not only drives but also monitors engine health, pulls over if something's wrong, and calls for help. That's what we'll build: a pipeline that's robust, debuggable, and won't wake you up.

I remember the first time I set up a Jenkins pipeline for a critical microservice. It was 2 AM, I was on call, and the build had been failing silently for hours. The pipeline looked clean—stages for build, test, deploy—but it had no error handling, no notifications, and no way to recover. The team was deploying from local machines, and the 'CI/CD' was a joke. That night, I learned the hard way that a pipeline without production-grade practices is just a fancy script that will burn you.

After countless 3 AM incidents, I developed a set of patterns that transformed our Jenkins pipelines from fragile scripts into resilient, self-healing workflows. This article is the guide I wish I had back then: the exact syntax, the gotchas, the real-world incidents, and the debugging techniques that keep your sleep uninterrupted.

We'll start with the basics of Declarative Pipeline, then layer in production essentials: error handling, secret management, parallel execution, and shared libraries. By the end, you'll be able to write pipelines that not only work but survive the chaos of a real production environment.

1. Declarative Pipeline Structure: The Blueprint

Declarative Pipeline is the recommended way to define CI/CD in Jenkins. It enforces a strict structure: pipeline block, agent, stages, steps, and post. This structure makes pipelines readable and predictable. In production, you'll rarely need scripted syntax unless you're doing complex logic like dynamic stages or loops.

``groovy pipeline { agent any stages { stage('Build') { steps { echo 'Building...' } } } post { always { echo 'Pipeline finished' } } } ``

Notice the `post` block: it runs regardless of pipeline status. In production, you'll use failure, success, unstable, and changed conditions to send notifications, clean up resources, or trigger downstream jobs.

Key directives: agent (where to run), environment (variables), tools (Maven, JDK), options (timeout, retry), triggers (cron, webhook), parameters (user input), and stages. Each directive has specific syntax and behavior.

Common pitfalls: forgetting steps inside stage, using steps instead of script for Groovy code, and misplacing post outside pipeline. Always validate your Jenkinsfile with the Pipeline Syntax tool.

Production insight: Use options { timestamps() } to add timestamps to logs, options { buildDiscarder(logRotator(numToKeepStr: '10')) } to clean up old builds, and options { timeout(time: 1, unit: 'HOURS') } to prevent runaway pipelines.

Key takeaway: Declarative Pipeline is your foundation. Master its structure before moving to advanced features.

📊 Production Insight
Always set a timeout at the pipeline level to prevent infinite loops. Use buildDiscarder to manage storage costs. Add timestamps() for easier debugging.
🎯 Key Takeaway
Declarative Pipeline provides a clear, enforced structure that scales well in teams.
jenkins-pipeline-basics Jenkins Pipeline Component Layers Layered stack from shared libraries to execution Shared Libraries Global vars | Custom steps | Utility functions Pipeline Definition Declarative syntax | Stages | Steps Environment & Credentials Environment variables | Credential bindings | Secret text Execution Engine Agent nodes | Executors | Workspace Post-Execution Post actions | Notifications | Cleanup THECODEFORGE.IO
thecodeforge.io
Jenkins Pipeline Basics

2. Agent Allocation: Where Your Pipeline Runs

The agent directive tells Jenkins where to execute the pipeline. Options include any (any available agent), none (no global agent; each stage must specify its own), label (specific label), docker (run inside a container), and node (specific node name).

In production, avoid agent any for critical pipelines because it can lead to unpredictable execution environments. Instead, use labeled agents for specific workloads (e.g., 'linux', 'docker-host', 'high-mem').

Example of per-stage agents: ``groovy pipeline { agent none stages { stage('Build') { agent { label 'linux' } steps { sh 'make' } } stage('Test') { agent { docker 'maven:3.8.1-jdk-11' } steps { sh 'mvn test' } } stage('Deploy') { agent { label 'deploy-node' } steps { sh 'deploy.sh' } } } } ``

Notice agent none at the top: this forces each stage to declare its own agent, saving resources and ensuring the right environment.

Common issues: agent labels not matching, Docker images not pulled (network issues), and resource contention. Use the 'Pipeline: Stage View' plugin to see which agent each stage runs on.

Production insight: For Docker agents, always specify args '-v /var/run/docker.sock:/var/run/docker.sock' if you need Docker-in-Docker. Also, use reuseNode true in nested stages to avoid workspace churn.

Key takeaway: Explicit agent allocation per stage improves reliability and resource utilization.

📊 Production Insight
Use agent none at pipeline level and assign agents per stage. For Docker agents, mount the Docker socket carefully to avoid permission issues.
🎯 Key Takeaway
Per-stage agents give you control over execution environment and resource usage.

3. Environment Variables and Credentials: Keep Secrets Safe

Hardcoding secrets in Jenkinsfile is a security violation. Use Jenkins Credentials Store and the environment directive to inject them securely. The credentials() helper binds a credential to a variable.

Example: ``groovy pipeline { agent any environment { DOCKER_REGISTRY = 'registry.example.com' DOCKER_CRED = credentials('docker-cred-id') } stages { stage('Login') { steps { sh 'docker login -u $DOCKER_CRED_USR -p $DOCKER_CRED_PSW $DOCKER_REGISTRY' } } } } ``

Note: The credentials() helper creates two variables: DOCKER_CRED_USR and DOCKER_CRED_PSW. For secret text, it creates a single variable.

In production, use different credentials per environment (dev, staging, prod) and scope them appropriately. Rotate credentials regularly and use Jenkins' built-in credential types (Username with password, SSH key, secret file, etc.).

Common mistake: using withCredentials inside a script block instead of the environment directive. The environment directive is cleaner and supports masking in logs.

Production insight: For multi-branch pipelines, use environment with BRANCH_NAME to select different credentials per branch. Example: ``groovy environment { DEPLOY_CRED = "${BRANCH_NAME == 'main' ? 'prod-cred' : 'dev-cred'}" } ``

Key takeaway: Always use Jenkins credentials store; never hardcode secrets. Use environment directive for declarative binding.

📊 Production Insight
Use conditional environment variables to pick credentials per branch. Rotate credentials regularly and limit scope to folders.
🎯 Key Takeaway
Secure credential management is non-negotiable in production pipelines.
jenkins-pipeline-basics Declarative vs Scripted Pipelines Trade-offs in syntax, flexibility, and maintainability Declarative Scripted Syntax Structured, predefined blocks Groovy-based, full control Error Handling Built-in post actions Try-catch-finally blocks Parallelism Declarative parallel directive Parallel map with closures Reusability Shared libraries via @Library Same, but more flexible Learning Curve Lower, easier for beginners Higher, requires Groovy knowledge THECODEFORGE.IO
thecodeforge.io
Jenkins Pipeline Basics

4. Stages and Steps: The Heart of Your Pipeline

Stages group related steps logically. Each stage should represent a phase in your CI/CD process: Build, Test, Deploy, etc. Steps are the actual commands (shell, docker, withCredentials, etc.).

In production, keep stages focused and idempotent. Each stage should be able to run independently, and the pipeline should handle partial failures gracefully.

Example of a robust stage: ``groovy stage('Build') { steps { script { try { sh 'make build' } catch (Exception e) { currentBuild.result = 'FAILURE' error("Build failed: ${e.message}") } } } post { failure { slackSend(color: 'danger', message: "Build failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}") } } } ``

Notice the script block wraps Groovy code. Use post inside stages for stage-specific cleanup. For Declarative, post can be at pipeline or stage level.

Common pitfalls: not using script for Groovy code (causes syntax errors), forgetting steps wrapper, and using return inside steps (not allowed).

Production insight: Use parallel for independent tasks (e.g., run unit tests in parallel). Example: ``groovy stage('Test') { parallel { stage('Unit') { steps { sh 'make test-unit' } } stage('Integration') { steps { sh 'make test-integration' } } } } ``

Key takeaway: Well-structured stages with proper error handling and parallelism make pipelines fast and reliable.

📊 Production Insight
Use parallel stages for independent tasks to reduce build time. Always handle errors at stage level with post actions.
🎯 Key Takeaway
Stages should be idempotent, focused, and include error handling.

5. Error Handling and Post Actions: Don't Let Failures Slide

In production, failures happen. Your pipeline must handle them explicitly. Declarative Pipeline provides post conditions: always, success, failure, unstable, changed, aborted, regression, fixed, and cleanup.

Example: ``groovy post { always { cleanWs() } failure { emailext( to: 'team@example.com', subject: "FAILURE: ${env.JOB_NAME} - ${env.BUILD_NUMBER}", body: "Check ${env.BUILD_URL}" ) } success { emailext( to: 'team@example.com', subject: "SUCCESS: ${env.JOB_NAME} - ${env.BUILD_NUMBER}", body: "Deployed to production" ) } } ``

For scripted blocks, use try-catch-finally. But prefer Declarative's post for readability.

Common mistake: relying on always to clean up but not handling failures specifically. Use failure to trigger alerts and success to trigger downstream jobs.

Production insight: Use post { cleanup } (Declarative 2.5+) for cleanup that runs even if the pipeline is aborted. Also, set currentBuild.result explicitly in scripted blocks to ensure post conditions fire correctly.

Key takeaway: Post actions are your safety net. Configure notifications and cleanup for every outcome.

📊 Production Insight
Use cleanup post condition for guaranteed cleanup. Set currentBuild.result in scripted blocks to trigger correct post actions.
🎯 Key Takeaway
Always define post actions for failure, success, and cleanup to avoid silent failures.

6. Shared Libraries: Reuse Pipeline Code Across Teams

Shared libraries allow you to define reusable pipeline code (functions, steps, etc.) in a separate repository and load them into any Jenkinsfile. This is essential for large organizations.

Structure
  • vars/ directory: define global variables (e.g., vars/buildApp.groovy defines a function buildApp).
  • src/ directory: define classes in Groovy.
  • resources/ directory: external files.

To use a shared library, configure it in Jenkins under Manage Jenkins > Configure System > Global Pipeline Libraries. Then in your Jenkinsfile: ```groovy @Library('my-shared-lib')_

pipeline { agent any stages { stage('Build') { steps { buildApp() } } } } ```

Production insight: Version your shared library with semantic versioning and use @Library('my-shared-lib@v1.2.3') to pin versions. Test library changes in a separate branch before updating the global default.

Common mistake: forgetting the underscore after the annotation (@Library('my-shared-lib')_). The underscore is required for syntax.

Key takeaway: Shared libraries reduce duplication and enforce best practices across teams.

📊 Production Insight
Pin shared library versions to avoid breaking changes. Use @Library('lib@branch') for testing.
🎯 Key Takeaway
Shared libraries enable consistent, reusable pipeline code across projects.

7. Triggers and Webhooks: Automate Pipeline Execution

Pipelines can be triggered automatically by SCM changes (webhooks), cron schedules, or upstream jobs. For production, use webhooks for immediate feedback and cron for periodic tasks.

Configure webhooks in your SCM (GitHub, GitLab, Bitbucket) to point to Jenkins. For Multibranch Pipelines, Jenkins automatically scans branches and creates pipelines.

Example of cron trigger: ``groovy pipeline { agent any triggers { cron('H /4 ') } stages { stage('Nightly Build') { steps { sh 'make nightly' } } } } ``

Use pollSCM('H /4 ') to check for changes periodically if webhooks are not possible.

Production insight: For webhooks, ensure your Jenkins URL is accessible from the SCM. Use shared secrets (e.g., GitHub webhook secret) to validate requests. Monitor webhook delivery in SCM settings.

Common issue: webhook not triggering due to network issues or incorrect URL. Check Jenkins logs for 'Received post' messages.

Key takeaway: Automate pipeline triggers with webhooks for speed and cron for scheduled tasks.

📊 Production Insight
Use webhooks for immediate triggers; fallback to pollSCM if webhooks are not feasible. Secure webhooks with secrets.
🎯 Key Takeaway
Automated triggers reduce manual intervention and speed up feedback loops.

8. Parallelism and Concurrency: Speed Up Your Pipeline

Parallel execution reduces build time by running independent stages simultaneously. Declarative Pipeline supports parallel inside a stage. You can also limit concurrency with lock or throttle plugins.

Example: ``groovy stage('Parallel Tests') { parallel { stage('Unit') { steps { sh 'make test-unit' } } stage('Integration') { steps { sh 'make test-integration' } } stage('Lint') { steps { sh 'make lint' } } } } ``

By default, if one parallel branch fails, the others continue. To fail fast, add failFast true: ``groovy parallel { failFast true stage('Unit') { ... } stage('Integration') { ... } } ``

Production insight: Use parallel for tasks that are truly independent. For resource-intensive tasks, use lock to limit concurrency (e.g., only one deployment at a time). Example: ``groovy stage('Deploy') { steps { lock('deploy-lock') { sh 'deploy.sh' } } } ``

Key takeaway: Parallelism speeds up pipelines, but use locks for critical sections to avoid race conditions.

📊 Production Insight
Use failFast true to stop all parallel branches on failure. Use lock for resource contention.
🎯 Key Takeaway
Parallel stages cut build time; locks prevent deployment conflicts.

9. Pipeline Durability: Surviving Jenkins Restarts

Jenkins Pipeline is designed to survive master restarts. The pipeline state is persisted in the Jenkins home directory. However, you must ensure your pipeline is durable: avoid non-serializable data in pipeline variables, and use @NonCPS annotations for non-serializable code.

Declarative Pipeline automatically handles serialization. In scripted pipeline, be careful with closures and complex objects.

Example of non-serializable issue: ``groovy def myObject = new SomeNonSerializableClass() stage('Bad') { steps { script { myObject.doSomething() // may cause NotSerializableException } } } ``

Fix: use @NonCPS annotation on the method that uses non-serializable objects, or avoid storing them in variables that cross stage boundaries.

Production insight: Enable 'Pipeline: Stage View with persistence' plugin to ensure stage metadata survives restarts. Also, use options { durabilityHint 'PERFORMANCE_OPTIMIZED' } for better performance at the cost of some durability.

Key takeaway: Design pipelines to be serializable; test by restarting Jenkins during a build.

📊 Production Insight
Test pipeline durability by restarting Jenkins while a build is running. Use @NonCPS for non-serializable code.
🎯 Key Takeaway
Durable pipelines survive restarts; avoid non-serializable data across stages.

10. Testing Your Pipeline: Jenkinsfile Unit Tests

Treat your Jenkinsfile as code: test it. Use tools like pipelineUnit or JenkinsPipelineUnit to unit test your pipeline logic. You can mock steps and verify behavior.

Example using JenkinsPipelineUnit (Spock): ``groovy class TestPipeline extends DeclarativePipelineTest { @Test void testBuildStage() { def script = loadScript('Jenkinsfile') script.execute() assertJobStatusSuccess() assertThat(script, hasStage('Build')) } } ``

In production, test your Jenkinsfile in a separate repository with a test pipeline that validates syntax and logic. Use the 'Pipeline Syntax' tool to generate step snippets.

Common mistake: not testing error handling paths. Write tests that simulate failures and verify post actions are triggered.

Production insight: Run pipeline tests in a CI job before merging changes to the Jenkinsfile. Use Blue Ocean or Stage View to visually inspect the pipeline.

Key takeaway: Test your pipeline code like any other code to catch issues early.

📊 Production Insight
Use JenkinsPipelineUnit for unit tests. Run pipeline tests in a CI job before merging.
🎯 Key Takeaway
Pipeline as code requires testing; use unit tests and syntax validation.

11. Monitoring and Observability: Know What's Happening

Production pipelines need monitoring. Integrate with monitoring tools (Prometheus, Grafana) using the Jenkins Metrics plugin. Export pipeline duration, success/failure rates, and queue time.

Set up alerts for pipeline failures, long build times, and agent availability. Use the 'Pipeline: Stage View' plugin to visualize each stage's duration and logs.

Example of sending metrics to Prometheus: ``groovy stage('Metrics') { steps { script { def start = System.currentTimeMillis() // ... build steps ... def duration = System.currentTimeMillis() - start // send duration to Prometheus via pushgateway sh """ echo "pipeline_duration_seconds{job='${env.JOB_NAME}',build='${env.BUILD_NUMBER}'} ${duration/1000}" | \ curl --data-binary @- http://pushgateway:9091/metrics/job/jenkins """ } } } ``

Production insight: Use the 'Build Timeout' plugin to set timeouts per stage. Monitor agent disk space and memory to prevent failures.

Key takeaway: Observability helps you detect issues before they become incidents.

📊 Production Insight
Export pipeline metrics to Prometheus. Set up alerts for failure rate and duration anomalies.
🎯 Key Takeaway
Monitor pipeline health with metrics and alerts.

12. Advanced Patterns: Blue-Green Deployments, Canary, and Rollbacks

Production-grade pipelines often include advanced deployment strategies. Blue-green deployment runs two identical environments; canary deploys to a subset of users; rollback reverts to a previous version.

Example of blue-green deployment stage: ``groovy stage('Blue-Green Deploy') { environment { ACTIVE = sh(script: 'kubectl get svc myapp -o jsonpath="{.spec.selector.version}"', returnStdout: true).trim() NEW = ACTIVE == 'blue' ? 'green' : 'blue' } steps { sh "kubectl apply -f deployment-${NEW}.yaml" sh "kubectl rollout status deployment/myapp-${NEW}" sh "kubectl patch svc myapp -p '{\"spec\":{\"selector\":{\"version\":\"${NEW}\"}}}'" } post { failure { sh "kubectl rollout undo deployment/myapp-${NEW}" } } } ``

Production insight: Use canary deployments with gradual traffic shifting (e.g., using Istio or Flagger). Always have a rollback plan and test it.

Common mistake: not verifying the new deployment health before switching traffic. Add readiness probes and health checks.

Key takeaway: Advanced deployment patterns reduce risk; always include automated rollback.

📊 Production Insight
Implement canary with traffic mirroring. Test rollback procedure regularly.
🎯 Key Takeaway
Blue-green and canary deployments minimize downtime; rollback is mandatory.
● Production incidentPOST-MORTEMseverity: high

The Silent Credential Rotation That Broke Deployments

Symptom
Pipeline shows 'SUCCESS' but no new version deployed. Logs show 'Authentication failed' for Docker registry but pipeline continues.
Assumption
We assumed the pipeline would fail if credentials were invalid. The scripted block used a try-catch that swallowed the exception.
Root cause
The Docker login command used a stored credential ID that had been rotated. The pipeline had a generic catch block that printed the error but didn't fail the stage.
Fix
Replace generic catch with specific exception handling and add a post failure block to send alerts. Also, add a credential check stage that validates credentials before deployment.
Key lesson
  • Never trust a pipeline that reports success without verifying the outcome.
  • Always validate critical steps (like Docker login) with explicit checks and ensure exceptions are not swallowed.
Production debug guideReal-world failure patterns and how to fix them fast3 entries
Symptom · 01
Pipeline hangs indefinitely with no output
Fix
Check for missing agent labels or offline nodes. Use Jenkins.instance.nodes in Script Console to verify node status. If using Kubernetes, ensure pods are not stuck in Pending.
Symptom · 02
Stage fails with 'script returned exit code 1' but no details
Fix
Wrap shell steps in try-catch and print stderr. Add sh(script: '...', returnStdout: true) to capture output. Check for missing environment variables or permissions.
Symptom · 03
Pipeline stuck in 'Waiting for input'
Fix
Use Jenkins.instance.getItemByFullName('job/path').getBuildByNumber(123).log to see input parameters. Cancel and restart with correct input, or use build --input in CLI.
★ Jenkins Pipeline Quick Debug Cheat SheetImmediate actions for common pipeline failures
Pipeline not starting
Immediate action
Check Jenkins logs for queue errors
Commands
`java -jar jenkins-cli.jar -s http://jenkins:8080/ who-am-i`
Fix now
Restart Jenkins or clear the build queue via Script Console: Jenkins.instance.queue.clear()
Agent offline+
Immediate action
Verify agent connectivity from master
Commands
`ping <agent-host>` or `ssh <agent-user>@<agent-host>`
Fix now
Restart agent process: java -jar agent.jar -jnlpUrl http://jenkins:8080/computer/<agent-name>/slave-agent.jnlp
Stage fails with 'timeout'+
Immediate action
Identify which step is hanging
Commands
`ps aux | grep jenkins` on agent to find stuck processes
Fix now
Kill the stuck process and add timeout to the step: timeout(60) { sh '...' }
Jenkins Pipeline Basics: Feature Comparison
featurescripted_pipelineproduction_recommendation
Declarative PipelineScripted PipelineUse Declarative for 90% of cases
SyntaxGroovy code with nodes/stage/stepDeclarative: structured DSL
Error Handlingtry-catch-finallyDeclarative: post conditions
SerializationManual @NonCPS neededDeclarative: automatic
ReadabilityLess readable for complex logicDeclarative: more readable
FlexibilityFull Groovy powerScripted for dynamic pipelines
Parallelismparallel() functionBoth support parallel
📦 Downloadable Quick Reference

Print-friendly master reference covering all topics in this track.

⇩ Download PDF

Key takeaways

1
Use Declarative Pipeline for its structure and built-in error handling.
2
Always use Jenkins Credentials Store for secrets.
3
Assign agents per stage for better resource control.
4
Implement post actions for every outcome (success, failure, cleanup).
5
Use shared libraries to reuse pipeline code across teams.
6
Test your pipeline code with unit tests and syntax validation.
7
Add monitoring and alerts for pipeline health.
8
Design for durability
avoid non-serializable data across stages.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is the difference between Declarative and Scripted Pipeline? When w...
Q02SENIOR
How do you handle secrets in Jenkins Pipeline?
Q03SENIOR
Explain how to set up a Multibranch Pipeline with GitHub webhooks.
Q04SENIOR
How would you implement a blue-green deployment in a Jenkins Pipeline?
Q05SENIOR
What is a shared library and how do you version it?
Q06SENIOR
How do you debug a pipeline that hangs?
Q07SENIOR
What causes 'java.io.NotSerializableException' in pipelines and how do y...
Q08SENIOR
Describe how to set up pipeline monitoring with Prometheus.
Q01 of 08JUNIOR

What is the difference between Declarative and Scripted Pipeline? When would you use each?

ANSWER
Declarative Pipeline uses a structured, predefined syntax with a 'pipeline' block, making it simpler and easier to read, ideal for most standard CI/CD workflows. Scripted Pipeline is more flexible and uses Groovy-based code, allowing complex logic and custom conditions, which is better for advanced or non-standard automation tasks. I default to Declarative for clarity and maintainability, but switch to Scripted when I need dynamic pipeline generation or intricate error handling that Declarative cannot easily express.
FAQ · 8 QUESTIONS

Frequently Asked Questions

01
What is the difference between Declarative and Scripted Pipeline?
02
How do I pass variables between stages?
03
How can I run a pipeline only on specific branches?
04
What is the best way to clean workspace after a build?
05
How do I trigger a pipeline from another pipeline?
06
Can I use Docker in a Jenkins Pipeline?
07
How do I handle flaky tests in pipeline?
08
What is the purpose of the `post` section?
N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Everything here is grounded in real deployments.

Follow
Verified
production tested
July 15, 2026
last updated
2,406
articles · all by Naren
🔥

That's Jenkins. Mark it forged?

8 min read · try the examples if you haven't

Previous
Jenkins Plugins
8 / 41 · Jenkins
Next
Jenkinsfile: Declarative Pipeline