15 Jenkins Pipeline Templates for Faster Production
15 copy-ready Declarative Jenkinsfile templates: Docker agents, parallel and matrix tests, image push, Kubernetes deploy, Terraform and shared libraries.
A Jenkins pipeline template is a reusable Jenkinsfile pattern for a common job, such as building and testing, building a Docker image, deploying to Kubernetes or running parallel tests. The 15 templates below use Declarative Pipeline syntax, so you can copy one into a repository, change the tool names and credentials IDs, and run it as a Pipeline or Multibranch Pipeline job.
Each template lists the plugins it needs and the mistakes to avoid. They build on each other: start with template 1 and add stages from the others as your delivery process grows. For how pipelines are designed at large companies, see our pillar on CI/CD pipeline examples from big tech companies.
Key takeaways
- Keep the Jenkinsfile in the application repository so the pipeline is versioned and reviewed with the code.
- Run builds on agents, not the controller, and use container agents so the toolchain is defined in an image.
- Use
optionsfor timeouts and build retention,whenfor branch rules, andpostfor cleanup and notifications. - Store secrets in Jenkins credentials and read them with
withCredentialsorcredentials(). Never echo them. - When three or more repositories share a pipeline, move it into a shared library and keep each Jenkinsfile to a few lines.
- Pin plugin and tool versions and test pipeline changes on a branch before merging.
Templates at a glance
| # | Template | Use it for | Main plugins |
|---|---|---|---|
| 1 | Basic build and test | Any project starting with CI | Pipeline, JUnit |
| 2 | Container agent build | Reproducible toolchains | Docker Pipeline |
| 3 | Maven with tools block | Java projects on static agents | Pipeline |
| 4 | Node.js with caching of dependencies | Front-end and Node services | Docker Pipeline |
| 5 | Parallel test stages | Slow test suites | Pipeline |
| 6 | Matrix build | Multiple OS or runtime versions | Pipeline (matrix) |
| 7 | Build and push Docker image | Containerised services | Docker Pipeline, Credentials Binding |
| 8 | Deploy to Kubernetes | Kubernetes workloads | Kubernetes, Credentials Binding |
| 9 | Kubernetes pod agents | Elastic build capacity | Kubernetes |
| 10 | Branch-based promotion with approval | Staging and production gates | Pipeline (input) |
| 11 | Code quality gate | SonarQube analysis | SonarQube Scanner |
| 12 | Security scanning | Dependency and image scanning | Pipeline |
| 13 | Terraform plan and apply | Infrastructure as code | Credentials Binding |
| 14 | Ansible deployment | VM and bare-metal deployments | Ansible or SSH Agent |
| 15 | Shared library pipeline | Many repositories with one standard | Pipeline: Shared Groovy Libraries |
Our list of Jenkins plugins that make CI/CD easier explains the plugins named here. Credential IDs, image names and URLs in the examples are placeholders.
1. Basic build and test
The starting point for any repository. It checks out code (automatic in a Multibranch or "Pipeline script from SCM" job), builds, tests, publishes JUnit results and cleans up.
pipeline {
agent { label 'linux' }
options {
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
disableConcurrentBuilds()
}
stages {
stage('Build') {
steps { sh 'make build' }
}
stage('Test') {
steps { sh 'make test' }
post {
always { junit 'reports/**/*.xml' }
}
}
}
post {
always { cleanWs() }
}
}
The timeout stops hung builds from blocking an executor, and buildDiscarder stops old builds filling the controller's disk. cleanWs() comes from the Workspace Cleanup plugin.
2. Container agent build
Instead of installing tools on agents, run each stage in an image. Anyone can reproduce the build with the same image.
pipeline {
agent {
docker {
image 'python:3.12-slim'
args '-u root'
}
}
stages {
stage('Install') {
steps { sh 'pip install -r requirements.txt' }
}
stage('Test') {
steps { sh 'pytest --junitxml=reports/results.xml' }
}
}
post {
always { junit 'reports/*.xml' }
}
}
This needs the Docker Pipeline plugin and an agent with Docker installed. Running as root inside the container is a shortcut; for shared agents, build an image with a matching non-root user.
3. Maven with a tools block
On static agents, the tools directive puts a Jenkins-managed JDK and Maven on the PATH. The names must match those in Manage Jenkins, Tools.
pipeline {
agent any
tools {
jdk 'jdk-21'
maven 'maven-3.9'
}
stages {
stage('Build and test') {
steps { sh 'mvn -B -ntp clean verify' }
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}
}
post {
always { junit 'target/surefire-reports/*.xml' }
}
}
-B runs Maven in batch mode and -ntp hides download progress, which keeps logs readable.
4. Node.js with dependency caching
Downloading every npm package on every build is slow. Mounting a cache directory into the container keeps the npm cache between builds on the same agent.
pipeline {
agent {
docker {
image 'node:22-alpine'
args '-v npm-cache:/root/.npm'
}
}
environment {
CI = 'true'
}
stages {
stage('Install') { steps { sh 'npm ci' } }
stage('Lint') { steps { sh 'npm run lint' } }
stage('Test') { steps { sh 'npm test' } }
stage('Build') { steps { sh 'npm run build' } }
}
}
npm ci installs exactly what the lock file says, which is what you want in CI.
5. Parallel test stages
Split independent work so it runs at the same time on separate agents.
pipeline {
agent none
stages {
stage('Tests') {
failFast true
parallel {
stage('Unit') {
agent { label 'linux' }
steps { sh 'make unit-test' }
}
stage('Integration') {
agent { label 'linux' }
steps { sh 'make integration-test' }
}
stage('Lint') {
agent { label 'linux' }
steps { sh 'make lint' }
}
}
}
}
}
failFast true aborts the other branches as soon as one fails. Our tips to build faster Jenkins pipelines cover more speed-ups.
6. Matrix build
The matrix directive runs the same stages across combinations of values, such as runtime versions and operating systems.
pipeline {
agent none
stages {
stage('Test matrix') {
matrix {
axes {
axis {
name 'PYTHON'
values '3.11', '3.12', '3.13'
}
}
agent {
docker { image "python:${PYTHON}-slim" }
}
stages {
stage('Test') {
steps {
sh 'pip install -r requirements.txt'
sh 'pytest'
}
}
}
}
}
}
}
Add an excludes block to skip combinations you do not support.
7. Build and push a Docker image
Tag images with something traceable, such as the build number or commit, and push with registry credentials stored in Jenkins.
pipeline {
agent { label 'docker' }
environment {
IMAGE = "registry.example.com/team/orders"
TAG = "${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}"
}
stages {
stage('Build image') {
steps { sh 'docker build -t $IMAGE:$TAG .' }
}
stage('Push image') {
when { branch 'main' }
steps {
withCredentials([usernamePassword(credentialsId: 'registry-creds',
usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) {
sh '''
echo "$REG_PASS" | docker login registry.example.com -u "$REG_USER" --password-stdin
docker push $IMAGE:$TAG
'''
}
}
}
}
post {
always { sh 'docker logout registry.example.com || true' }
}
}
Use single quotes around shell scripts that reference secrets. With double quotes, Groovy interpolates the secret into the command string, and Jenkins warns about it. For writing the Dockerfile itself, see our Dockerfile examples.
8. Deploy to Kubernetes
Deploy the image built earlier by updating the Deployment, then wait for the rollout so a failed deploy fails the build.
pipeline {
agent { label 'linux' }
parameters {
string(name: 'TAG', description: 'Image tag to deploy')
}
stages {
stage('Deploy') {
steps {
withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) {
sh '''
kubectl -n orders set image deployment/orders orders=registry.example.com/team/orders:$TAG
kubectl -n orders rollout status deployment/orders --timeout=180s
'''
}
}
}
}
post {
failure {
withCredentials([file(credentialsId: 'kubeconfig-staging', variable: 'KUBECONFIG')]) {
sh 'kubectl -n orders rollout undo deployment/orders'
}
}
}
}
Many teams move this step to a GitOps tool such as Argo CD, where Jenkins only updates the image tag in a Git repository. That keeps cluster credentials out of Jenkins.
9. Kubernetes pod agents
With the Kubernetes plugin, each build gets a fresh pod with the containers it needs, and the pod is deleted afterwards.
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ["sleep"]
args: ["infinity"]
- name: kubectl
image: bitnami/kubectl:latest
command: ["sleep"]
args: ["infinity"]
'''
}
}
stages {
stage('Build') {
steps {
container('maven') { sh 'mvn -B -ntp package' }
}
}
stage('Check cluster access') {
steps {
container('kubectl') { sh 'kubectl version --client' }
}
}
}
}
Set CPU and memory requests on these containers so the cluster can schedule them predictably, and pin image tags instead of latest. Scaling agents this way is covered in best practices for scaling Jenkins agents.
10. Branch-based promotion with manual approval
Deploy every main branch build to staging automatically, then wait for a named group to approve production.
pipeline {
agent { label 'linux' }
stages {
stage('Build') { steps { sh 'make build' } }
stage('Deploy staging') {
when { branch 'main' }
steps { sh './deploy.sh staging' }
}
stage('Approve production') {
when { branch 'main' }
agent none
options { timeout(time: 1, unit: 'DAYS') }
input {
message 'Deploy to production?'
ok 'Deploy'
submitter 'release-managers'
}
steps { echo 'Approved' }
}
stage('Deploy production') {
when { branch 'main' }
steps { sh './deploy.sh production' }
}
}
}
Putting input in a stage with agent none means no executor is held while the pipeline waits.
11. Code quality gate with SonarQube
pipeline {
agent any
tools { maven 'maven-3.9' }
stages {
stage('Analyse') {
steps {
withSonarQubeEnv('sonarqube') {
sh 'mvn -B -ntp verify sonar:sonar'
}
}
}
stage('Quality gate') {
steps {
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
}
}
withSonarQubeEnv and waitForQualityGate come from the SonarQube Scanner plugin. The quality gate step needs a webhook configured from SonarQube back to Jenkins.
12. Security scanning stage
Add dependency and image scanning so known vulnerabilities fail the build before deployment. This example uses Trivy from its official image; swap in the scanner your team uses.
pipeline {
agent { label 'docker' }
environment { IMAGE = 'registry.example.com/team/orders:candidate' }
stages {
stage('Build image') {
steps { sh 'docker build -t $IMAGE .' }
}
stage('Scan filesystem') {
steps {
sh 'docker run --rm -v "$PWD":/src aquasec/trivy:latest fs --exit-code 1 --severity HIGH,CRITICAL /src'
}
}
stage('Scan image') {
steps {
sh 'docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest image --exit-code 1 --severity HIGH,CRITICAL $IMAGE'
}
}
}
}
Mounting the Docker socket gives the scanner control of the agent's Docker daemon, so only do this on dedicated build agents. Our comparison of image scanning tools lists alternatives.
13. Terraform plan and apply
pipeline {
agent {
docker {
image 'hashicorp/terraform:1.9'
args '--entrypoint='
}
}
environment {
AWS_ACCESS_KEY_ID = credentials('aws-access-key-id')
AWS_SECRET_ACCESS_KEY = credentials('aws-secret-access-key')
}
stages {
stage('Init and validate') {
steps {
sh 'terraform init -input=false'
sh 'terraform validate'
}
}
stage('Plan') {
steps {
sh 'terraform plan -input=false -out=tfplan'
archiveArtifacts 'tfplan'
}
}
stage('Apply') {
when { branch 'main' }
input { message 'Apply this plan?' }
steps { sh 'terraform apply -input=false tfplan' }
}
}
}
Applying the saved tfplan guarantees that what was reviewed is what gets applied. Use a remote backend with state locking; on AWS, prefer short-lived credentials from an assumed role over long-lived access keys.
14. Ansible deployment to servers
pipeline {
agent { label 'ansible' }
stages {
stage('Syntax check') {
steps { sh 'ansible-playbook -i inventories/staging site.yml --syntax-check' }
}
stage('Deploy') {
steps {
sshagent(credentials: ['deploy-ssh-key']) {
sh 'ansible-playbook -i inventories/staging site.yml --diff'
}
}
}
}
}
sshagent (SSH Agent plugin) loads the private key for the duration of the step only. Run with --check first on production inventories if your roles support check mode.
15. Shared library pipeline
Once several repositories copy the same Jenkinsfile, move the logic into a shared library. A file vars/standardPipeline.groovy in the library repository:
def call(Map config = [:]) {
pipeline {
agent { label config.get('agent', 'linux') }
options { timeout(time: 30, unit: 'MINUTES') }
stages {
stage('Build') { steps { sh config.get('buildCmd', 'make build') } }
stage('Test') { steps { sh config.get('testCmd', 'make test') } }
}
post { always { cleanWs() } }
}
}
Each application's Jenkinsfile then shrinks to:
@Library('[email protected]') _
standardPipeline(buildCmd: 'mvn -B -ntp package', testCmd: 'mvn -B -ntp verify')
Pin the library to a tag so a change to the library does not break every project at once. Configure the library under Manage Jenkins, System, Global Trusted Pipeline Libraries.
Choosing a starting template
| Your situation | Start with | Add next |
|---|---|---|
| First CI job for a repository | 1 or 2 | 5 when tests get slow |
| Service deployed as a container | 2 and 7 | 12, then 8 or a GitOps tool |
| Library supporting several versions | 6 | 11 |
| Infrastructure repository | 13 | Policy checks before apply |
| Ten repositories with copied Jenkinsfiles | 15 | Version the library and test it on a branch |
Practices that apply to every template
- Use Declarative syntax unless you need logic it cannot express; then use a
scriptblock or a shared library function, not a whole Scripted pipeline. - Validate Jenkinsfiles before pushing with the pipeline linter (
jenkins-cli declarative-linteror the REST endpoint). - Set the controller's executor count to zero so builds never run on it.
- Keep credentials scoped to the folder that needs them.
- Record test results and artifacts so failures can be investigated after the workspace is gone.
Our 20 Jenkins best practices and common CI/CD pipeline failures and fixes go further. If you are preparing for interviews, the Jenkins pipeline design interview questions test the same patterns. You can build these pipelines hands-on in our Jenkins training, in Kharadi, Pune or live online.
Frequently asked questions
What is a Jenkins pipeline template?
It is a reusable Jenkinsfile pattern for a common delivery task, such as build and test, Docker image publishing or Kubernetes deployment. You copy it into a repository or call it from a shared library and adjust names, tools and credentials.
Should I use Declarative or Scripted pipeline syntax?
Use Declarative for most pipelines. It has a fixed structure, built-in options, when conditions and post sections, and it is easier to read and validate. Use script blocks or shared library code only for logic Declarative cannot express.
How do I reuse one pipeline across many repositories?
Put the pipeline in a Jenkins shared library, usually as a global variable in the vars directory, and call it from a short Jenkinsfile with the @Library annotation. Pin the library version with a tag.
How do I keep secrets safe in a Jenkinsfile?
Store them as Jenkins credentials and access them with withCredentials or the credentials() helper. Use single-quoted shell strings so Groovy does not interpolate the secret, and never print it.
How do I run Jenkins stages in parallel?
Wrap stages in a parallel block inside a parent stage. Give each branch its own agent if they should run on different machines, and set failFast true to stop the others when one fails.
Can Jenkins run builds in Docker containers?
Yes. With the Docker Pipeline plugin, agent docker runs a stage or the whole pipeline in an image. With the Kubernetes plugin, each build can run in a temporary pod with several containers.
How do I add a manual approval step in Jenkins?
Add an input directive to a stage with a message and optional submitter list. Put that stage on agent none and add a timeout so it does not hold an executor or wait forever.
What plugins do these templates need?
Most need Pipeline and Git. Others need Docker Pipeline, Kubernetes, Credentials Binding, JUnit, Workspace Cleanup, SonarQube Scanner, SSH Agent or Pipeline: Shared Groovy Libraries, depending on the template.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0