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.
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.
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').
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.
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.
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.
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')_
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.
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.
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 @NonCPSannotations 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.
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
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.
Q02 of 08SENIOR
How do you handle secrets in Jenkins Pipeline?
ANSWER
I store secrets in Jenkins' built-in Credentials Binding plugin, referencing them via withCredentials blocks to inject environment variables or files securely. For sensitive values like API keys, I use the secret text credential type and never hardcode them in the Jenkinsfile or source control. I also integrate with external secret managers like HashiCorp Vault using the Vault plugin for dynamic, short-lived secrets.
Q03 of 08SENIOR
Explain how to set up a Multibranch Pipeline with GitHub webhooks.
ANSWER
In Jenkins, create a Multibranch Pipeline job pointing to your GitHub repository, then configure the GitHub webhook to send push events to Jenkins' GitHub webhook URL (typically http://your-jenkins/github-webhook/). Ensure the GitHub plugin is installed and the webhook secret matches between GitHub and Jenkins for security. The pipeline automatically scans branches and pull requests matching your defined strategies, triggering builds on each push.
Q04 of 08SENIOR
How would you implement a blue-green deployment in a Jenkins Pipeline?
ANSWER
I would define two identical environments (blue and green) with separate load balancer target groups. In the Jenkins pipeline, I'd build and deploy the new version to the inactive environment, run smoke tests against it, then switch the load balancer to route traffic to the updated environment. After a cooldown period, I'd keep the old environment ready for immediate rollback by simply switching the load balancer back.
Q05 of 08SENIOR
What is a shared library and how do you version it?
ANSWER
A shared library in DevOps, particularly in CI/CD tools like Jenkins, is a collection of reusable pipeline code—such as functions, steps, or entire workflows—stored in a version control repository. You version it by tagging releases in Git (e.g., v1.0.0) and referencing that specific tag in your pipeline configuration, which ensures stability and traceability across different projects.
Q06 of 08SENIOR
How do you debug a pipeline that hangs?
ANSWER
I start by checking the pipeline logs at the point of failure, looking for any repeated output or missing heartbeats that indicate a stuck step. Then I SSH into the build agent or pod to inspect running processes, resource usage (CPU/memory/disk), and network connectivity, often using tools like top, strace, or lsof. If the hang is intermittent, I add verbose logging or timeout wrappers around suspect commands, and I review any external service calls or file locks that could cause deadlocks. Finally, I check the CI/CD tool's own health and agent queue to rule out infrastructure issues like exhausted disk space or zombie processes.
Q07 of 08SENIOR
What causes 'java.io.NotSerializableException' in pipelines and how do you fix it?
ANSWER
This exception occurs when a pipeline stage tries to serialize an object that doesn't implement the Serializable interface, often when passing data between stages in distributed processing frameworks like Spark or Flink. To fix it, either make the class implement Serializable, mark the non-serializable field as transient, or restructure the pipeline to avoid passing that object across stage boundaries.
Q08 of 08SENIOR
Describe how to set up pipeline monitoring with Prometheus.
ANSWER
To set up pipeline monitoring with Prometheus, I expose custom metrics from CI/CD tools like Jenkins or GitLab via a Prometheus exporter, then scrape those endpoints in the Prometheus server configuration. I define key pipeline metrics such as build duration, success/failure rates, and queue times using a client library in the pipeline scripts. Finally, I create PromQL queries and alerting rules to detect anomalies like stuck jobs or frequent failures, and visualize them in Grafana dashboards for real-time observability.
01
What is the difference between Declarative and Scripted Pipeline? When would you use each?
JUNIOR
02
How do you handle secrets in Jenkins Pipeline?
SENIOR
03
Explain how to set up a Multibranch Pipeline with GitHub webhooks.
SENIOR
04
How would you implement a blue-green deployment in a Jenkins Pipeline?
SENIOR
05
What is a shared library and how do you version it?
SENIOR
06
How do you debug a pipeline that hangs?
SENIOR
07
What causes 'java.io.NotSerializableException' in pipelines and how do you fix it?
SENIOR
08
Describe how to set up pipeline monitoring with Prometheus.
SENIOR
FAQ · 8 QUESTIONS
Frequently Asked Questions
01
What is the difference between Declarative and Scripted Pipeline?
Declarative provides a simpler, structured syntax with built-in error handling. Scripted offers full Groovy flexibility but is more complex. Use Declarative for most cases.
Was this helpful?
02
How do I pass variables between stages?
Use environment variables or script blocks. In Declarative, use environment directive. For complex data, write to a file and read in the next stage.
Was this helpful?
03
How can I run a pipeline only on specific branches?
Use `when` directive:when { branch 'main' }. For Multibranch Pipeline, it automatically matches branches.
Was this helpful?
04
What is the best way to clean workspace after a build?
Use post { always { cleanWs() } } in Declarative or cleanWs() in scripted. This ensures workspace is cleaned regardless of build result.
Was this helpful?
05
How do I trigger a pipeline from another pipeline?
Use `build job: 'downstream-job', wait: false in a stage. For declarative, use build` step inside a script block.
Was this helpful?
06
Can I use Docker in a Jenkins Pipeline?
Yes, use agent { docker 'image:tag' } to run inside a container. You can also use docker.image().inside() in scripted.
Was this helpful?
07
How do I handle flaky tests in pipeline?
Use retry(3) { sh 'run tests' } to retry failed steps. Also, consider using test reporting to mark build as unstable instead of failure.
Was this helpful?
08
What is the purpose of the `post` section?
post defines actions to run after all stages, based on the pipeline result (success, failure, etc.). It's used for notifications, cleanup, and triggering downstream jobs.