Shared Libraries for Reusable Code
What you'll learn: How to extract common Jenkins Pipeline logic into shared libraries that multiple pipelines can use, ensuring consistency and reducing duplication.
The Core Problem
Imagine copying the same pipeline code—authentication steps, deployment logic, notification patterns—across dozens of Jenkins jobs. When you need to update that logic, you'd have to modify every single pipeline. Shared libraries solve this by letting you write the code once and reference it everywhere.
What Are Shared Libraries?
A shared library in Jenkins is a separate repository containing reusable Groovy code that your pipelines can import and call. Think of it like a toolkit: instead of building the same hammer for every project, you create one hammer everyone can use.
These libraries typically contain:
- vars/: Global variables (custom pipeline steps)
- src/: Traditional Groovy classes
- resources/: Non-Groovy files like scripts or templates
How They Work
You define your library in Jenkins settings (globally or per-folder), then load it in your pipeline:
@Library('my-shared-lib') _
pipeline {
agent any
stages {
stage('Deploy') {
steps {
// Call custom step from shared library
deployToKubernetes(environment: 'staging')
}
}
}
}
Inside vars/deployToKubernetes.groovy in your library:
def call(Map config) {
echo "Deploying to ${config.environment}"
// Common deployment logic here
}
The Benefits
Shared libraries create a single source of truth for common patterns. Update your notification logic once, and all pipelines using it automatically get the improvement. Teams can standardize on approved deployment strategies, security checks, and quality gates without copy-pasting.
Key Takeaway: Shared libraries centralize reusable pipeline logic into importable code repositories, ensuring consistency across all your Jenkins pipelines while dramatically reducing duplication and maintenance burden.