Overview and What You Will Learn
A declarative Jenkins pipeline is a Jenkinsfile stored in your repository that describes your build, test and deploy stages in a fixed, validated structure. Jenkins reads it, schedules each stage on an agent, and reports the result. In this lab, you will build one Jenkinsfile in steps: parallel validation stages on Docker agents, an image build that is scanned before it is pushed, credential binding for deployments, a production approval gate, post-build notifications, a shared library, and a Kubernetes agent that builds without a Docker socket.
- Structuring a declarative pipeline with
agent noneand per-stage agents - Running parallel stages and publishing test results
- Building, scanning and pushing an image in the right order
- Binding credentials safely with
withCredentials - Adding an approval gate that does not hold an executor
- Reusing steps with a shared library and running builds on Kubernetes agents
Why This Matters in Production
Many enterprises, such as banks and insurers, run Jenkins on their own infrastructure because policy forbids sending source code or artifacts to a hosted CI service. At a company like Razorpay, engineers who can write a clean declarative pipeline, protect credentials and gate production deploys can work productively in that environment from the first week. A badly written Jenkinsfile, on the other hand, leaks secrets into build logs, ties up executors, and deploys unscanned images.
Core Principles
Jenkins has a controller and many agents. The controller hosts the UI, schedules jobs and stores credentials, and it should run no builds itself. Agents do the work, and each stage of a pipeline can run on a different agent.
UI, scheduling, credentials] --> A1[Static agent
docker-builder] C --> A2[Docker agent
container per stage] C --> A3[Kubernetes agent
pod per build] classDef ctl fill:#326CE5,color:#FFFFFF classDef agent fill:#DBEAFE,color:#1E293B class C ctl class A1,A2,A3 agent
Start the pipeline with agent none and give each stage its own agent. A global agent would run every stage on the same machine, even stages that need different tools, and it prevents parallel stages from using separate machines.
The pipeline built in this lab runs in this order. Scanning happens before the push, so a vulnerable image never reaches the registry, and a person approves before production:
parallel] --> B[Build, scan
and push] B --> S[Deploy
staging] S --> AP{Approve?} AP -->|Yes| P[Deploy
production] classDef stage fill:#326CE5,color:#FFFFFF classDef gate fill:#F97316,color:#FFFFFF classDef prod fill:#10B981,color:#FFFFFF class V,B,S stage class AP gate class P prod
Detailed Step-by-Step Practical Lab
This lab assumes a Jenkins controller with the Pipeline, Docker Pipeline, Credentials Binding and Slack plugins, a multibranch pipeline job pointing at your repository, an agent labelled docker-builder that has Docker, the AWS CLI and Trivy installed, and an agent labelled k8s-deployer that has Helm and kubectl. The when { branch 'main' } conditions only work in multibranch pipelines. Inside Groovy strings, \\ produces a single backslash, so shell line continuations keep working.
Milestone 1 - The Skeleton
Create a Jenkinsfile in the repository root. Global settings live in environment and options:
pipeline { agent none environment { ECR_REGISTRY = '123456789012.dkr.ecr.ap-south-1.amazonaws.com' IMAGE_NAME = 'payment-api' AWS_REGION = 'ap-south-1' } options { timeout(time: 30, unit: 'MINUTES') buildDiscarder(logRotator(numToKeepStr: '20')) disableConcurrentBuilds() timestamps() } stages { // Milestones 2 to 5 add stages here, in order }}Jenkins rejects an empty stages block, so add Milestone 2 before you run it.
Milestone 2 - Parallel Validation on Docker Agents
Each parallel branch runs in its own container. Unit tests publish a JUnit report, and each stage cleans its own workspace:
stage('Validate') { parallel { stage('Unit Tests') { agent { docker { image 'node:20-alpine' } } steps { sh 'npm ci' sh 'npm test -- --reporter=junit --outputFile=junit.xml' } post { always { junit 'junit.xml' cleanWs() } } } stage('Lint') { agent { docker { image 'node:20-alpine' } } steps { sh 'npm ci && npm run lint' } post { always { cleanWs() } } } stage('Dependency Scan') { agent { docker { image 'aquasec/trivy:0.56.2' args '--entrypoint=' } } steps { sh 'trivy fs --exit-code 1 --severity HIGH,CRITICAL --no-progress .' } post { always { cleanWs() } } } } }Pin the Trivy image to a specific tag instead of latest, so a new release cannot change your build overnight.
Milestone 3 - Build, Scan, Then Push
The image is built on a dedicated builder agent, scanned locally, and pushed only if the scan is clean. Registry login uses the agent's IAM role, so there is no stored secret:
stage('Build and Push') { agent { label 'docker-builder' } steps { script { env.IMAGE_VERSION = GIT_COMMIT.substring(0, 8) env.IMAGE_TAG = "${ECR_REGISTRY}/${IMAGE_NAME}:${env.IMAGE_VERSION}" } sh ''' docker build -t "$IMAGE_TAG" . trivy image --exit-code 1 --severity HIGH,CRITICAL --no-progress "$IMAGE_TAG" aws ecr get-login-password --region "$AWS_REGION" \\ | docker login --username AWS --password-stdin "$ECR_REGISTRY" docker push "$IMAGE_TAG" ''' } post { always { cleanWs() } } }The shell script uses single-quoted Groovy so that $IMAGE_TAG is expanded by the shell, not interpolated by Groovy. A Docker daemon on the agent is a powerful privilege, so use a dedicated, short-lived builder machine, or the Kubernetes approach in Milestone 7.
Milestone 4 - Deploy to Staging with a File Credential
Store each cluster's kubeconfig as a Jenkins secret file credential. withCredentials writes it to a temporary file, points KUBECONFIG at it, and deletes it afterwards:
stage('Deploy Staging') { agent { label 'k8s-deployer' } when { branch 'main' } steps { withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) { sh ''' helm upgrade --install payment-api ./charts/payment-api \\ --namespace payment-api-staging \\ --set image.repository="$ECR_REGISTRY/$IMAGE_NAME" \\ --set image.tag="$IMAGE_VERSION" \\ --atomic --timeout 5m ''' } } post { always { cleanWs() } } }The --atomic flag rolls the release back automatically if it does not become healthy in time.
Milestone 5 - Approval Gate and Production Deploy
The approval runs in a stage with agent none, so waiting for a person does not occupy an executor. The timeout stops a forgotten approval from hanging forever:
stage('Approve Production') { agent none when { branch 'main' } steps { timeout(time: 24, unit: 'HOURS') { input message: 'Deploy to production?', ok: 'Deploy now', submitter: 'tech-leads,senior-engineers' } } } stage('Deploy Production') { agent { label 'k8s-deployer' } when { branch 'main' } steps { withCredentials([file(credentialsId: 'kubeconfig-production', variable: 'KUBECONFIG')]) { sh ''' helm upgrade --install payment-api ./charts/payment-api \\ --namespace payment-api-production \\ --set image.repository="$ECR_REGISTRY/$IMAGE_NAME" \\ --set image.tag="$IMAGE_VERSION" \\ --atomic --timeout 10m ''' } } post { always { cleanWs() } } }Milestone 6 - Post Conditions for Notifications
Add a post section after the stages block. At the pipeline level with agent none, there is no workspace, so only steps that need no node, such as notifications, belong here. Workspace cleanup stays in each stage:
post { success { slackSend(channel: '#deployments', color: 'good', message: "SUCCESS: ${env.JOB_NAME} #${env.BUILD_NUMBER} ${env.IMAGE_VERSION ?: ''}") } failure { slackSend(channel: '#deployments', color: 'danger', message: "FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER} ${env.BUILD_URL}console") } }Common MistakePutting
cleanWs()in a pipeline-levelpostblock when the pipeline usesagent none. There is no workspace there, so the step fails with a missingFilePathcontext. Clean up inside each stage's ownpost.
Milestone 7 - Shared Library
A shared library holds steps that many pipelines reuse. Put it in its own repository with this layout, and register it under Manage Jenkins, System, Global Trusted Pipeline Libraries:
jenkins-shared-library/ vars/ deployToKubernetes.groovy notifySlack.groovy src/ com/company/HelmDeploy.groovy// vars/deployToKubernetes.groovydef call(Map config) { def releaseName = config.releaseName ?: error('releaseName is required') def imageTag = config.imageTag ?: error('imageTag is required') def credentialsId = config.credentialsId ?: error('credentialsId is required') def namespace = config.namespace ?: 'default' def chart = config.chart ?: './charts/app' def valuesFile = config.valuesFile ?: 'values.yaml' withCredentials([file(credentialsId: credentialsId, variable: 'KUBECONFIG')]) { sh """ helm upgrade --install ${releaseName} ${chart} \\ --namespace ${namespace} \\ --values ${valuesFile} \\ --set image.tag=${imageTag} \\ --atomic --timeout 5m """ }}Load it by name and pin a version, then call it like a built-in step:
('jenkins-shared-library@v1.4.0') _ pipeline { agent { label 'k8s-deployer' } stages { stage('Deploy') { steps { deployToKubernetes( releaseName: 'payment-api', namespace: 'payment-api-staging', imageTag: env.GIT_COMMIT.substring(0, 8), credentialsId: 'kubeconfig-staging', valuesFile: 'charts/values-staging.yaml' ) } } }}Pinning @v1.4.0 means a change to the library's main branch cannot break every pipeline at once.
Milestone 8 - Dynamic Kubernetes Agents Without a Docker Socket
With the Kubernetes plugin, each build runs in a fresh pod. A daemonless builder such as Kaniko builds the image inside the pod, so nothing mounts the host's Docker socket. The pod's service account needs permission to push to the registry:
pipeline { agent { kubernetes { defaultContainer 'node' yaml '''apiVersion: v1kind: Podspec: serviceAccountName: jenkins-builder containers: - name: node image: node:20-alpine command: ['sleep', 'infinity'] - name: kaniko image: gcr.io/kaniko-project/executor:v1.23.2-debug command: ['/busybox/cat'] tty: true''' } } stages { stage('Test') { steps { sh 'npm ci && npm test' } } stage('Build Image') { steps { container('kaniko') { sh ''' /kaniko/executor \\ --context="dir://$WORKSPACE" \\ --destination="123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-api:$BUILD_NUMBER" ''' } } } }}Pin both images to exact tags, and check that the builder image you choose is still maintained before you rely on it.
Milestone 9 - Validate Before You Push
Lint the Jenkinsfile against your controller before committing, so syntax errors never reach the build queue:
curl -s -X POST -u "rahul:$JENKINS_API_TOKEN" \ -F "jenkinsfile=<Jenkinsfile" \ "$JENKINS_URL/pipeline-model-converter/validate"A valid file returns Jenkinsfile successfully validated. In the UI, the Replay link on a finished build lets you edit and rerun the pipeline without a new commit.
Production Best Practices & Common Pitfalls
Common MistakeDeclaring a global agent such as
agent { label 'linux' }. Every stage then runs on the same machine, tools collide, and parallel stages cannot use separate agents. Useagent noneat the top and declare an agent per stage.
SecurityNever print a credential with
echo, and never put it in a double-quoted Groovy string, because Groovy interpolation exposes it in logs and process lists. Jenkins masks injected credentials only on exact matches, so a Base64-encoded copy of a password is not masked.
TipThe Pipeline Syntax generator at
/pipeline-syntax/on your controller builds correct step code from a form for any installed plugin, which is faster than reading each plugin's documentation.
RememberA bare
inputinside a stage that has an agent holds an executor while it waits. Put approvals in a stage withagent none, and always wrap them in atimeout, so a forgotten approval cannot block the queue.
- Run zero executors on the controller. Builds on the controller can read credentials and the Jenkins home directory, so keep all work on agents.
- Scan before you push. A vulnerable image that is already in the registry can be pulled by mistake, so fail the build first.
- Prefer secret files and IAM roles to long-lived keys. Kubeconfig files bind as files, and cloud access can come from the agent's role instead of a stored secret.
- Avoid mounting
/var/run/docker.sock. It gives the build root on the host, so use dedicated builder machines or a daemonless builder. - Scope credentials. Store credentials in a folder-level scope and restrict who can use them, instead of making everything global.
- Pin everything. Pin container image tags, plugin versions and shared library versions so builds are reproducible.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Validate a Jenkinsfile | curl -X POST -u USER:TOKEN -F "jenkinsfile=<Jenkinsfile" URL/pipeline-model-converter/validate |
| Trigger a build | java -jar jenkins-cli.jar -s URL -auth USER:TOKEN build JOB |
| Stop running builds | java -jar jenkins-cli.jar -s URL -auth USER:TOKEN stop-builds JOB |
| List jobs | java -jar jenkins-cli.jar -s URL -auth USER:TOKEN list-jobs |
| Read the console log | curl -u USER:TOKEN URL/job/JOB/lastBuild/consoleText |
| Rerun with edits | Build page, then Replay |
| Problem | Cause | Fix |
|---|---|---|
Required context class hudson.FilePath is missing |
A node-only step ran under agent none |
Move the step into a stage with an agent |
when { branch } never matches |
Job is not a multibranch pipeline | Use a multibranch job or another condition |
| Build waits forever at approval | No timeout around input |
Wrap input in timeout |
| Docker stage cannot find Docker | Agent has no Docker or the plugin is missing | Use an agent label with Docker installed |
| Secret appears in the log | Credential used in a double-quoted string | Use single quotes and shell variables |