What is Shared Library in Jenkins: Explanation and Example
shared library in Jenkins is a reusable set of Groovy scripts and functions stored in a separate repository that multiple Jenkins pipelines can use. It helps keep pipeline code clean and consistent by sharing common logic across projects.How It Works
Think of a shared library in Jenkins like a toolbox that many people can use. Instead of each person carrying their own tools, they all share one big toolbox with useful tools inside. In Jenkins, this toolbox is a Git repository containing Groovy scripts and functions that pipelines can call.
When a Jenkins pipeline runs, it can load this shared library and use its functions just like calling a helper friend to do common tasks. This way, you avoid repeating the same code in every pipeline and make updates in one place that affect all pipelines using the library.
Example
This example shows how to define and use a simple shared library function in a Jenkins pipeline.
/* In the shared library repository under vars/greet.groovy */ def call(String name) { echo "Hello, ${name}! Welcome to Jenkins shared libraries." } /* In your Jenkinsfile */ library 'my-shared-library' pipeline { agent any stages { stage('Greet') { steps { greet('Alice') } } } }
When to Use
Use shared libraries when you have multiple Jenkins pipelines that need to perform similar tasks, like building, testing, or deploying software. Instead of copying the same code into each pipeline, put that code in a shared library.
This is helpful in large teams or organizations where many projects follow similar steps. It saves time, reduces errors, and makes maintenance easier because you update the shared code once and all pipelines benefit.
Key Points
- Shared libraries store reusable pipeline code in a separate Git repo.
- They help keep Jenkinsfiles simple and consistent.
- Functions in shared libraries can be called like normal pipeline steps.
- Updating the library updates all pipelines that use it.
- They improve collaboration and reduce duplication.