Jenkins Shared Libraries: vars, src, resources, @Library and Reusable Pipeline Steps
Why Shared Libraries
After a few projects every Jenkinsfile starts to look the same: checkout, build, test, scan, push, deploy. Copying that code means a fix must be made in every repository. A shared library is a Git repository of Groovy code that all pipelines load, so you fix it once.
| Without a library | With a library |
| 50 copies of the same stage | One step, dockerBuildPush(), used everywhere |
| Security fix needs 50 pull requests | One change, all pipelines get it (at the version they use) |
| Each team does it differently | A standard way, with sensible defaults |
| Long, hard-to-read Jenkinsfiles | Short Jenkinsfiles that read like a list of intentions |
Library Layout
text
jenkins-shared-lib/
├─ vars/ ← global steps: each file name becomes a step name
│ ├─ buildMaven.groovy
│ ├─ dockerBuildPush.groovy
│ ├─ notifySlack.groovy
│ ├─ standardPipeline.groovy ← a whole pipeline template
│ └─ notifySlack.txt ← optional help text
├─ src/ ← normal Groovy classes, packages
│ └─ org/example/
│ └─ Version.groovy
└─ resources/ ← non-code files
└─ org/example/
└─ deployment.yaml.tpl
| Folder | Use |
vars/ | Global steps you call like built-in ones. Most of your code goes here |
src/ | Plain Groovy classes with packages, for larger logic |
resources/ | Templates and scripts, read with libraryResource('org/example/file') |
Write Your First Step
groovy
// vars/notifySlack.groovy
def call(String status = currentBuild.currentResult, String channel = '#builds') {
def color = [SUCCESS: 'good', UNSTABLE: 'warning', FAILURE: 'danger'].get(status, '#999999')
slackSend channel: channel, color: color,
message: "${status}: ${env.JOB_NAME} #${env.BUILD_NUMBER} (<${env.BUILD_URL}|open>)"
}
The method called **call** makes the file name the step name. Use it as notifySlack() or notifySlack('FAILURE', '#alerts').
A Step With a Map of Options
groovy
// vars/dockerBuildPush.groovy
def call(Map cfg = [:]) {
def image = cfg.image ?: error('dockerBuildPush: image is required')
def tag = cfg.tag ?: env.BUILD_NUMBER
def registry = cfg.registry ?: 'registry.example.com'
def creds = cfg.credentialsId ?: 'registry-creds'
def context = cfg.context ?: '.'
withCredentials([usernamePassword(credentialsId: creds, usernameVariable: 'U', passwordVariable: 'P')]) {
sh '''
echo "$P" | docker login ''' + registry + ''' -u "$U" --password-stdin
'''
sh "docker build -t ${registry}/${image}:${tag} ${context}"
sh "docker push ${registry}/${image}:${tag}"
}
return "${registry}/${image}:${tag}"
}
Keep secrets safe: Do not interpolate a secret into a double-quoted Groovy string. Here the password stays in the environment variable P, read by the shell. Registry and image are not secrets, so they can be interpolated.
Use the Library in a Jenkinsfile
groovy
@Library('team-lib@v1.4.0') _
pipeline {
agent { label 'linux' }
stages {
stage('Build') { steps { buildMaven(goals: 'clean verify') } }
stage('Image') {
steps { script { env.IMAGE = dockerBuildPush(image: 'team/shop', tag: env.BUILD_NUMBER) } }
}
}
post { always { notifySlack() } }
}
@Library('name@version') _ loads it. The final underscore is needed when no import follows
@v1.4.0 can be a tag, branch or commit. Use tags in production so a library change does not break every build at once
- Without a version, the default version set in Jenkins is used
- To load inside the pipeline at runtime:
library('team-lib@main')
Configure the Library in Jenkins
- Go to Manage Jenkins → System → Global Trusted Pipeline Libraries (or at folder level)
- Click Add and give it a Name (
team-lib)
- Set a Default version (for example
main)
- Choose Modern SCM and pick Git, then set the repository URL and credentials
- Optionally allow Load implicitly, which loads it into every pipeline without
@Library
- Save
| Type | Sandbox |
| Global Trusted Libraries (Manage Jenkins) | Run outside the Groovy sandbox: full power, so only trusted admins may change the repository |
| Folder-level libraries | Run inside the sandbox, safer for team-owned libraries |
Classes in src
groovy
// src/org/example/Version.groovy
package org.example
class Version implements Serializable {
static String fromGit(def steps) {
def tag = steps.sh(script: 'git describe --tags --abbrev=0 2>/dev/null || echo 0.0.0', returnStdout: true).trim()
def sha = steps.sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
return "${tag}-${steps.env.BUILD_NUMBER}-${sha}"
}
}
groovy
// vars/appVersion.groovy
import org.example.Version
def call() { return Version.fromGit(this) }
- Classes that hold state across a restart must be
Serializable
- Pass
this (or steps) in so the class can call pipeline steps like sh
- Use
libraryResource to load a template file from resources/
groovy
def yaml = libraryResource('org/example/deployment.yaml.tpl')
writeFile file: 'deployment.yaml', text: yaml.replace('__IMAGE__', env.IMAGE)
A Whole-Pipeline Template
groovy
// vars/standardPipeline.groovy
def call(Map cfg = [:]) {
pipeline {
agent { label cfg.agent ?: 'linux' }
options { timeout(time: 30, unit: 'MINUTES'); buildDiscarder(logRotator(numToKeepStr: '20')) }
stages {
stage('Build and test') { steps { sh cfg.buildCommand ?: './mvnw -B verify' } }
stage('Image') {
when { branch 'main' }
steps { script { env.IMAGE = dockerBuildPush(image: cfg.image) } }
}
stage('Deploy staging') {
when { branch 'main' }
steps { sh "./deploy.sh staging ${env.IMAGE}" }
}
}
post { always { notifySlack() } }
}
}
groovy
// Jenkinsfile in the application repository: 3 lines
@Library('team-lib@v1.4.0') _
standardPipeline(image: 'team/shop', buildCommand: './mvnw -B verify')
Balance: Templates enforce a standard but can feel rigid. Provide options and hooks (extra stages, custom commands) so teams are not forced to fork the library.
Test and Release the Library
- Keep the library in Git with pull request review: it is production code for your whole company
- Use the Jenkins Pipeline Unit framework (
JenkinsPipelineUnit) to unit test vars steps with mocked steps
- Create a test Jenkinsfile in the library repository that loads the branch under change with
@Library('team-lib@my-branch')
- Release with semantic version tags and a changelog. Breaking changes mean a new major version
Common Mistakes
| Mistake | Fix |
Forgetting the _ after @Library('x') | Write @Library('x') _ |
Pipelines follow main of the library and break | Pin to a tag and upgrade deliberately |
| Whole logic as one giant step | Small steps with clear names; compose them |
Non-serializable objects kept across sh or input steps | Keep state in simple types or mark @NonCPS helpers carefully |
| Secrets printed by the library | Use withCredentials and never echo; rely on masking only as a safety net |
| No documentation | Add vars/step.txt help files and a README with examples |
Practice Tasks
- Create a Git repository with
vars/notifySlack.groovy and vars/buildMaven.groovy
- Register it in Manage Jenkins and load it with
@Library
- Add
dockerBuildPush with a map of options and defaults
- Create
standardPipeline and reduce one project's Jenkinsfile to a few lines
- Tag
v1.0.0, change a step, tag v1.1.0, and pin a project to each version in turn
Conclusion
A shared library holds reusable pipeline code in Git: vars/ for global steps, src/ for classes, resources/ for files. Load it with @Library('name@tag') _, pin versions with tags, keep secrets in credentials, and review and test the library like production code.
Quick Summary: layout vars/src/resources; def call(Map cfg); @Library('x@tag') _; global vs folder libs; src classes; libraryResource; standardPipeline; test + pin versions.