Advanced Jenkins: Enterprise Pipeline Patterns
· Pavan Y N · cicd, devops, kubernetes, docker
Basic Jenkins pipelines cover a single repository and a single team. Organizations with many repositories, several environments, and strict release rules need more: guarded deployment stages, approval gates, shared pipeline code, and a controller that stays healthy under load. EduGeek explains the advanced Declarative Pipeline features, shared libraries, and optimization techniques that matter at that scale.
The examples target the Jenkins LTS (long-term support) line 2.580.x, which requires Java 21 or Java 25. If Jenkins itself is new to you, start with the Jenkins CI/CD guide first.
# Declarative Pipeline advanced features
## Pipeline options
The options directive controls how Jenkins runs the whole pipeline.
pipeline {
agent any
options {
// Abort the whole build after one hour
timeout(time: 1, unit: 'HOURS')
// Keep only the last 10 builds
buildDiscarder(logRotator(numToKeepStr: '10'))
// Do not run two builds of the same job at once
disableConcurrentBuilds()
// Take over checkout instead of the automatic one
skipDefaultCheckout()
// Prefix console lines with timestamps
timestamps()
// Abort sibling parallel branches as soon as one fails
parallelsAlwaysFailFast()
// Keep stashes of the last 5 builds so "Restart from Stage" works
preserveStashes(buildCount: 5)
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
echo 'Building...'
}
}
}
}
A pipeline-level retry(3) option also exists, but it re-runs the entire pipeline, including deployments. Prefer retry on a single stage or step, which accepts conditions such as agent() to retry only when the build agent was lost.
## Advanced when conditions
when decides whether a stage runs. The branch condition only works in a Multibranch Pipeline, and tag conditions only match when the multibranch job is configured to discover tags. In a tag build, BRANCH_NAME holds the tag name, so a condition that requires both branch 'main' and a version tag can never be true; use the tag condition alone for release stages.
pipeline {
agent any
triggers {
cron('H 2 * * *')
}
stages {
stage('Deploy to dev') {
when { branch 'develop' }
steps {
echo 'Deploying to dev...'
}
}
stage('Deploy to staging') {
when {
allOf {
branch 'main'
not { changelog '.*\\[skip-staging\\].*' }
}
}
steps {
echo 'Deploying to staging...'
}
}
stage('Deploy to production') {
when {
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
}
steps {
echo 'Deploying a tagged release to production...'
}
}
stage('Nightly build') {
when { triggeredBy 'TimerTrigger' }
steps {
echo 'Running the nightly build...'
}
}
}
}
Three behaviors are worth knowing. when is evaluated after the stage's agent is entered unless beforeAgent true is set, so add it to stages with their own agent to avoid allocating an executor for a stage that will be skipped. An expression condition must return a boolean or null: returning the string 'false' still counts as true. And triggeredBy 'TimerTrigger' only fires when a triggers block (or job configuration) actually schedules the build.
## Input and approval gates
The input directive pauses a stage for a human decision. Jenkins applies a stage's options first, then input, and only then enters the stage's agent, so a pipeline waiting for approval does not occupy an executor. Put a timeout in the stage options so an unanswered prompt cannot wait forever.
pipeline {
agent none
stages {
stage('Build and test') {
agent any
steps {
echo 'Build and test...'
}
}
stage('Deploy to staging') {
agent any
steps {
echo 'Apply the staging manifests...'
}
}
stage('Deploy to production') {
agent any
options {
timeout(time: 1, unit: 'DAYS')
}
input {
id 'ProductionDeployment'
message 'Deploy to production?'
ok 'Deploy'
submitter 'admin,release-managers'
submitterParameter 'APPROVED_BY'
parameters {
string(name: 'REPLICAS', defaultValue: '3', description: 'Number of replicas')
booleanParam(name: 'RUN_SMOKE_TESTS', defaultValue: true, description: 'Run smoke tests after the rollout')
}
}
steps {
echo "Approved by ${APPROVED_BY}, replicas: ${REPLICAS}"
sh 'kubectl scale deployment/myapp --replicas=$REPLICAS'
script {
if (env.RUN_SMOKE_TESTS == 'true') {
echo 'Running smoke tests...'
}
}
}
}
}
}
The values entered in the prompt become environment variables inside that stage only, and submitterParameter records who approved. The submitter list is a comma-separated set of users or external group names. Gates like this work well for a short list of approvers; for broader release control, consider moving production changes into a reviewed pull request instead (see the GitOps guide).
# Shared libraries
A shared library keeps common pipeline code in one repository so that hundreds of Jenkinsfiles stay short.
## Library structure
jenkins-shared-library/
├── vars/
│ ├── buildDockerImage.groovy
│ ├── deployToKubernetes.groovy
│ └── sendNotification.groovy
├── src/
│ └── com/
│ └── company/
│ └── Notifications.groovy
└── resources/
└── scripts/
└── deploy.sh
vars/ holds global variables that behave like steps, src/ holds ordinary Groovy classes on the pipeline classpath, and resources/ holds files read with the libraryResource step. Keep the library small, and do not redefine built-in steps such as sh or timeout: the Jenkins best-practices guide warns against both.
## Building images
// vars/buildDockerImage.groovy
def call(Map config) {
def imageName = config.imageName ?: error('imageName is required')
def imageTag = config.imageTag ?: env.BUILD_NUMBER
def registry = config.registry ?: ''
def fullName = registry ? "${registry}/${imageName}:${imageTag}" : "${imageName}:${imageTag}"
def buildArgs = (config.buildArgs ?: [:]).collect { k, v -> "--build-arg ${k}=${v}" }.join(' ')
echo "Building Docker image: ${fullName}"
sh "docker build -f ${config.dockerfile ?: 'Dockerfile'} -t ${fullName} ${buildArgs} ${config.context ?: '.'}"
if (config.push) {
echo 'Pushing image to the registry...'
sh "docker push ${fullName}"
}
return fullName
}
The step expects the caller to be logged in to the registry already, for example inside docker.withRegistry. It no longer pushes a latest tag, because a mutable tag makes it impossible to tell which build is running; deploy by an immutable tag or digest.
## Deploying to Kubernetes
// vars/deployToKubernetes.groovy
def call(Map config) {
def namespace = config.namespace ?: error('namespace is required')
def deployment = config.deployment ?: error('deployment is required')
def image = config.image ?: error('image is required')
def timeout = config.timeout ?: '5m'
withCredentials([file(credentialsId: config.kubeconfigId ?: 'kubeconfig', variable: 'KUBECONFIG')]) {
withEnv(["K_NS=${namespace}", "K_DEPLOY=${deployment}", "K_IMAGE=${image}", "K_TIMEOUT=${timeout}"]) {
try {
sh 'kubectl set image deployment/$K_DEPLOY $K_DEPLOY=$K_IMAGE -n $K_NS'
sh 'kubectl rollout status deployment/$K_DEPLOY -n $K_NS --timeout=$K_TIMEOUT'
} catch (err) {
sh 'kubectl rollout undo deployment/$K_DEPLOY -n $K_NS'
error("Rollout of ${deployment} failed and was rolled back: ${err.message}")
}
}
}
}
This is a rolling update with a rollback on failure. Values reach the shell as environment variables inside single-quoted sh strings, so a branch name or parameter containing shell metacharacters cannot inject commands.
Blue-green and canary releases are deliberately not implemented here. A canary needs weighted traffic splitting and metric analysis, which a second Deployment and a sleep do not provide. Controllers built for that job, such as Argo Rollouts or Flagger, run inside the cluster and are usually driven from Git; the GitOps guide shows a Flagger canary.
## Notifications
// vars/sendNotification.groovy
def call(Map config) {
def status = config.status ?: currentBuild.currentResult
def channel = config.channel ?: '#deployments'
def message = config.message ?: buildMessage(status)
slackSend(
color: getColor(status),
channel: channel,
message: message,
tokenCredentialId: 'slack-token'
)
if (config.email && (status == 'FAILURE' || status == 'UNSTABLE')) {
emailext(
to: config.email,
subject: "Build ${status}: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: "Build ${status}: ${env.BUILD_URL}",
mimeType: 'text/plain'
)
}
}
def buildMessage(status) {
return "*${env.JOB_NAME}* build #${env.BUILD_NUMBER}: ${status} (<${env.BUILD_URL}|open>)"
}
def getColor(status) {
switch (status) {
case 'SUCCESS': return 'good'
case 'FAILURE': return 'danger'
case 'UNSTABLE': return 'warning'
default: return '#808080'
}
}
Use currentBuild.currentResult when reading the build status. The currentBuild.result property is null during ordinary stages until something sets it (it is populated inside post blocks), so code that may run in either place is safer with currentResult, which is never null.
## Using the library
@Library('jenkins-shared-library@main') _
pipeline {
agent any
environment {
REGISTRY = 'registry.example.com'
IMAGE_NAME = 'myapp'
NAMESPACE = 'production'
}
stages {
stage('Build and push') {
steps {
script {
docker.withRegistry("https://${env.REGISTRY}", 'registry-credentials') {
env.IMAGE_REF = buildDockerImage(
imageName: env.IMAGE_NAME,
imageTag: "${env.BUILD_NUMBER}",
registry: env.REGISTRY,
push: true
)
}
}
}
}
stage('Deploy') {
when { branch 'main' }
steps {
script {
deployToKubernetes(
namespace: env.NAMESPACE,
deployment: env.IMAGE_NAME,
image: env.IMAGE_REF,
timeout: '10m'
)
}
}
}
}
post {
always {
script {
sendNotification(status: currentBuild.currentResult, email: 'team@example.com')
}
}
}
}
In Declarative Pipeline, calls to global variables from a library belong inside a script block. Pin @main to a tag or commit for production pipelines. A library configured globally is trusted: it can call any Java, Groovy, or Jenkins API, so anyone who can push to its repository has unlimited access to Jenkins. Libraries configured at folder level run in the Groovy sandbox instead.
# Pipeline optimization
## Parallel execution
Run independent stages side by side, and stop the rest when one fails. The Jenkins CI/CD guide has a full example using Docker agents with reuseNode true; the essential structure is:
pipeline {
agent any
options {
parallelsAlwaysFailFast()
}
stages {
stage('Checks') {
parallel {
stage('Unit tests') {
steps {
echo 'npm run test:unit'
}
}
stage('Static analysis') {
steps {
echo 'sonar-scanner'
}
}
stage('Dependency audit') {
steps {
echo 'npm audit --audit-level=high'
}
}
}
}
}
}
## Matrix builds
Matrix builds are covered, with a corrected Docker-agent example, in the Jenkins CI/CD guide. The rule that trips up most first attempts is that axis values can be used in a cell's agent directive, but variables from the cell's own environment block cannot.
## Caching and stashing
pipeline {
agent any
stages {
stage('Build') {
steps {
sh '''
docker build \
--cache-from myapp:latest \
--build-arg BUILDKIT_INLINE_CACHE=1 \
-t myapp:${BUILD_NUMBER} \
.
'''
stash name: 'build-output', includes: 'dist/**'
}
}
stage('Test') {
parallel {
stage('Unit tests') {
agent { label 'test-runner' }
steps {
unstash 'build-output'
sh 'npm run test:unit'
}
}
stage('Integration tests') {
agent { label 'test-runner' }
steps {
unstash 'build-output'
sh 'npm run test:integration'
}
}
}
}
}
}
stash and unstash move files between agents within one run. The step is designed for small files: stashes are compressed TAR archives handled by the controller, and the Jenkins documentation advises considering alternatives once a stash reaches roughly 5 to 100 MB. For larger or longer-lived outputs, use archiveArtifacts or an external repository manager such as Nexus or Artifactory. Docker layer caching only helps when the image used for --cache-from is present on the agent, which is another reason to prefer long-lived agents or a registry-backed cache for image builds.
# Running Jenkins at scale
These practices come from the Jenkins documentation and the plugin catalog rather than from any single deployment.
- →Keep Groovy light. Pipeline Groovy always executes on the controller. Use
shsteps for heavy work, parse large files with shell tools on the agent, and make HTTP calls withcurlon the agent rather than from Groovy. - →Use disposable agents. Kubernetes and Docker agents avoid shared workspaces. The Jenkins best-practices guide advises against sharing workspaces between builds.
- →Discard old builds. Set
buildDiscarderinoptionsso build records do not accumulate. - →Scan repositories automatically. The GitHub Branch Source plugin provides organization folders that create Multibranch jobs for the repositories of a GitHub organization, and the GitLab Branch Source plugin offers the equivalent for GitLab.
- →Control access by role. The Matrix Authorization Strategy plugin or the Role-based Authorization Strategy plugin restricts who can configure, build, or administer folders.
- →Define the controller as code. Configuration as Code and a pinned
plugins.txtlet the controller be rebuilt from Git. - →Measure the controller. The Prometheus metrics plugin exposes a scrape endpoint for Prometheus, and the OpenTelemetry plugin publishes metrics and distributed traces of job executions. See the Prometheus guide for collection and alerting.
- →Treat shared libraries like products. Version them with tags, keep them small, and document each step.
# Key takeaways
- →Use
inputas a stage directive with atimeoutinoptions, because Jenkins evaluates it before allocating the stage's agent and an unattended approval then holds no executor. - →Do not combine
branch 'main'with atagcondition in onewhenblock, because tag builds report the tag name asBRANCH_NAME. - →Put reusable steps in a shared library under
vars/, call them from ascriptblock, and pin the library to a tag or commit. - →Pass values to shell commands through environment variables and single-quoted
shstrings so pipeline parameters cannot inject commands. - →Read
currentBuild.currentResultrather thancurrentBuild.resultfor the build status, becauseresultisnulluntil it is set. - →Implement canary and blue-green releases with a controller that splits traffic and analyzes metrics, not with extra Deployments and a
sleepin Groovy. - →Keep
stashfor small files and usearchiveArtifactsor an artifact repository for large outputs.
# Further reading
Test yourself: Advanced Jenkins Patterns assessment