Skip links

How to Improve Your Jenkins Builds with Shared Libraries

Jump To Section

What is a Shared Library?

A shared library in Jenkins is a reusable collection of Groovy scripts that can be used by multiple Jenkins jobs. This allows you to share code and functionality between different jobs, which can make your builds more efficient and easier to maintain.

To understand the concept of shared libraries, let’s consider a real-time example. Imagine you have multiple Jenkins pipelines that require a common set of functions for interacting with a version control system, such as Git. Instead of duplicating the Git-related code in each pipeline, you can create a shared library that encapsulates the necessary Git operations.

Folder Structure of Shared Library

image 6
Folder Structure Used in Shared Library
  1. The src directory is structured like a standard Java project. This means that you can use the import statement to import classes from other directories in the src directory.
  2. The vars directory is a special directory that contains global variables that are defined in the shared library. These variables can be accessed from any Jenkins job that imports the shared library.
  3. The resources directory is a regular directory that can contain any type of file. However, it is typically used to store static resources that are used by the shared library.

Steps to Configure Shared Library in Jenkins

Create a repository in any source code management tool.

Here we are using GitHub.

image 4

Clone the newly created repository

git clone
image 8

Create a folder structure

cd shared-lib
# create a master branch (optional)
git branch master
git checkout master
# create vars directory
mkdir vars
cd vars

We have created the vars directory in which we are going to write our reusable function.

Let’s consider a real-time example. Imagine you have multiple Jenkins pipelines that require a common set of functions for interacting with a version control system, such as Git. Instead of duplicating the Git-related code in each pipeline, you can create a shared library that encapsulates the necessary Git operations.

Creating your First Shared Library to checkout scm.


def call(String repoUrl, String branch){
def workingDir = "${env.WORKSPACE}"
sh "git clone ${repoUrl} ${workingDir}"
sh "git checkout ${branch}"
return workingDir
  1. The call method, which is a special method in Jenkins shared library that allows the function to be directly called from a Jenkins pipeline.
  2. ${env.WORKSPACE} assigns the Jenkins environment variable WORKSPACE
  3. sh is used to execute a shell command to clone the repository in the workingDir and checkout(switch) to the specified branch .
  4. the path workingDir is returned to Jenkins Pipeline.

This piece of functionality can be reused in Jenkins pipelines that import and use the shared library.

Commit your changes to a Git repository.

git add .
git commit -m "checkout scm fucntionality added"
git push origin master
image 9

The code is successfully pushed and available in the remote repository.

image 10

Configure the Global pipeline Libraries (Shared Library) in Jenkins

Login to Jenkins.

Go to Manage Jenkins → Configure System

image 1

Next Step, Search for Global Pipeline Libraries and configure the parameters.

image 2
  1. Enter the Shared Library Name: shared-lib
  2. Set the default branch: master (Jenkins will consider the default branch if no branch is specified while importing shared lib).
image 5

3. Configure the repository we created for Shared Library:

GitHub – tejashreeSalvi/shared-lib: Jenkins shared library

4. Configure the credentials, if your repository is private

5. Click Save

WoW! we are done with configuration part.

Let’s use the shared library in pipelines

To Import the library we use the @Library annotation and specify the library name defined in the Jenkins Global Configuration.

Create a Jenkins pipeline

Go to New Item and give a suitable pipeline name first-shared-lib-pipeline and Type pipeline

image 12

Click on OK

Script to Import the Shared Library

Go to Pipeline Script→ Add the Script and Save@Library(“shared-lib@master”) _

pipeline {
agent any
stages {
stage('Code Checkout') {
steps {
script {
def workingDir = checkoutCode("", "develop")
echo $workingDir
  1. @Library("shared-lib@master") _: this will import the shared library named “shared-lib” at the “master” branch. The library is made available for use in this Jenkins pipeline.

2. def workingDir = checkoutCode("", "develop"): This line calls the checkoutCode function from the shared library, passing the repository URL and Branch name.

Hence you can create multiple pipelines and use the checkoutCode function from a shared library to checkout scm. Instead of writing the block of code again and again in all the Jenkins pipelines.

image 3

Build the Pipeline.

Go to first-shared-lib-pipeline → Click on Build Now


The build will be triggered. Check the console output of the build.

image 11

If you look closely, you will find that the Shared library was loaded successfully.

image 7

By using the shared library and calling the checkoutCode function, this pipeline script performs a code checkout operation by cloning the specified repository and switching to the develop branch.

Hurray! We have created our first reusable code using Shared Library.

When to use and When to not use Shared Library.

image 12

That’s it! We have learned basics about Shared Library. Hope you will use it in your next project.


Install Jenkins

Picture of Tejashree Salvi

Tejashree Salvi

Suggested Reading

Ready to Unlock Your Enterprise's Full Potential?

Michael Woodall

Chief Growth Officer of Financial Services

Michael Woodall, as the Chief Growth Officer of Financial Services at Altimetrik, spearheads the identification of new growth avenues and revenue streams within the financial services sector. With a robust background and extensive expertise, Michael brings invaluable insights to his role.

Previously, Michael served as the Chief of Operations and President of the Trust Company at Putnam Investments, where he orchestrated strategic developments and continuous operational enhancements. Leveraging strategic partnerships and data analytics, he revolutionized capabilities across investments, retail and institutional distribution, and client services. Under his leadership, Putnam received numerous accolades, including the DALBAR Mutual Fund Service Award for over 30 consecutive years.

Michael’s dedication to industry evolution is evident through his involvement with prestigious organizations such as the DTCC Senior Wealth Advisory Board, ICI Operations Committee, and NICSA, where he served as Chairman and now holds the position of Director Emeritus. Widely recognized as an industry luminary, Michael frequently shares his expertise with various divisions of the SEC, solidifying his reputation as a seasoned presenter.

At Altimetrik, Michael plays a pivotal role in driving expansion within financial services, leveraging his expertise and Altimetrik’s Digital Business Methodology to ensure clients navigate their digital journey seamlessly, achieving tangible outcomes and exponential growth.

Beyond his corporate roles, Michael serves as Chair of the Boston Water & Sewer Commission, appointed by the Mayor of Boston, and is actively involved in various philanthropic endeavors, including serving on the board of the nonprofit Inspire Arts & Music.

Michael holds a distinguished business degree from Northeastern University, graduating with distinction as a member of the Sigma Epsilon Rho Honor Society.

Anguraj Kumar Arumugam

Chief Digital Business Officer for the U.S. West region

Anguraj is an accomplished business executive with an extensive leadership experience in the services industry and strong background across digital transformation, engineering services, data and analytics, cloud and consulting.

Prior to joining Altimetrik, Anguraj has served in various positions and roles at Globant, GlobalLogic, Wipro and TechMahindra. Over his 25 years career, he has led many strategic and large-scale digital engineering and transformation programs for some of world’s best-known brands. His clients represent a range of industry sectors including Automotive, Technology and Software Platforms. Anguraj has built and guided all-star teams throughout his tenure, bringing together the best of the techno-functional capabilities to address critical client challenges and deliver value.

Anguraj holds a bachelor’s degree in mechanical engineering from Anna University and a master’s degree in software systems from Birla Institute of Technology, Pilani.

In his spare time, he enjoys long walks, hiking, gardening, and listening to music.

Vikas Krishan

Chief Digital Business Officer and Head of the EMEA region

Vikas (Vik) Krishan serves as the Chief Digital Business Officer and Head of the EMEA region for Altimetrik. He is responsible for leading and growing the company’s presence across new and existing client relationships within the region.

Vik is a seasoned executive and brings over 25 years of global experience in Financial Services, Digital, Management Consulting, Pre- and Post-deal services and large/ strategic transformational programmes, gained in a variety of senior global leadership roles at firms such as Globant, HCL, Wipro, Logica and EDS and started his career within Investment Banking. He has developed significant cross industry experience across a wide variety of verticals, with a particular focus on working with and advising the C-Suite of Financial Institutions, Private Equity firms and FinTech’s on strategy and growth, operational excellence, performance improvement and digital adoption.

He has served as the engagement lead on multiple global transactions to enable the orchestration of business, technology, and operational change to drive growth and client retention.

Vik, who is based in London, serves as a trustee for the Burma Star Memorial Fund, is a keen photographer and an avid sportsman.

Megan Farrell Herrmanns

Chief Digital Officer, US Central

Megan is a senior business executive with a passion for empowering customers to reach their highest potential. She has depth and breadth of experience working across large enterprise and commercial customers, and across technical and industry domains. With a track record of driving measurable results, she develops trusted relationships with client executives to drive organizational growth, unlock business value, and internalize the use of digital business as a differentiator.

At Altimetrik, Megan is responsible for expanding client relationships and developing new business opportunities in the US Central region. Her focus is on digital business and utilizing her experience to create high growth opportunities for clients. Moreover, she leads the company’s efforts in cultivating and enhancing our partnership with Salesforce, strategically positioning our business to capitalize on new business opportunities.

Prior to Altimetrik, Megan spent 10 years leading Customer Success at Salesforce, helping customers maximize the value of their investments across their technology stack. Prior to Salesforce, Megan spent over 15 years with Accenture, leading large transformational projects for enterprise customers.

Megan earned a Bachelor of Science in Mechanical Engineering from Marquette University. Beyond work, Megan enjoys playing sand volleyball, traveling, watching her kids soccer games, and is actively involved in a philanthropy (Advisory Council for Cradles to Crayons).

Adaptive Clinical Trial Designs: Modify trials based on interim results for faster identification of effective drugs.Identify effective drugs faster with data analytics and machine learning algorithms to analyze interim trial results and modify.
Real-World Evidence (RWE) Integration: Supplement trial data with real-world insights for drug effectiveness and safety.Supplement trial data with real-world insights for drug effectiveness and safety.
Biomarker Identification and Validation: Validate biomarkers predicting treatment response for targeted therapies.Utilize bioinformatics and computational biology to validate biomarkers predicting treatment response for targeted therapies.
Collaborative Clinical Research Networks: Establish networks for better patient recruitment and data sharing.Leverage cloud-based platforms and collaborative software to establish networks for better patient recruitment and data sharing.
Master Protocols and Basket Trials: Evaluate multiple drugs in one trial for efficient drug development.Implement electronic data capture systems and digital platforms to efficiently manage and evaluate multiple drugs or drug combinations within a single trial, enabling more streamlined drug development
Remote and Decentralized Trials: Embrace virtual trials for broader patient participation.Embrace telemedicine, virtual monitoring, and digital health tools to conduct remote and decentralized trials, allowing patients to participate from home and reducing the need for frequent in-person visits
Patient-Centric Trials: Design trials with patient needs in mind for better recruitment and retention.Develop patient-centric mobile apps and web portals that provide trial information, virtual support groups, and patient-reported outcome tracking to enhance patient engagement, recruitment, and retention
Regulatory Engagement and Expedited Review Pathways: Engage regulators early for faster approvals.Utilize digital communication tools to engage regulatory agencies early in the drug development process, enabling faster feedback and exploration of expedited review pathways for accelerated approvals
Companion Diagnostics Development: Develop diagnostics for targeted recruitment and personalized treatment.Implement bioinformatics and genomics technologies to develop companion diagnostics that can identify patient subpopulations likely to benefit from the drug, aiding in targeted recruitment and personalized treatment
Data Standardization and Interoperability: Ensure seamless data exchange among research sites.Utilize interoperable electronic health record systems and health data standards to ensure seamless data exchange among different research sites, promoting efficient data aggregation and analysis
Use of AI and Predictive Analytics: Apply AI for drug candidate identification and data analysis.Leverage AI algorithms and predictive analytics to analyze large datasets, identify potential drug candidates, optimize trial designs, and predict treatment outcomes, accelerating the drug development process
R&D Investments: Improve the drug or expand indicationsUtilize computational modelling and simulation techniques to accelerate drug discovery and optimize drug development processes