Skip links

How to Improve Your Jenkins Builds with Shared Libraries

Jump To Section

How to Improve Your Jenkins Builds with Shared Libraries

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 https://github.com/tejashreeSalvi/shared-lib.git
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.

checkoutCode.groovy

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: https://github.com/tejashreeSalvi/shared-lib.git

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("https://github.com/tejashreeSalvi/django-todo-cicd.git", "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("https://github.com/tejashreeSalvi/django-todo-cicd.git", "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

image

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.

Pre-requisites

Install Jenkins

Picture of Tejashree Salvi

Tejashree Salvi

Subscribe

Suggested Reading

Ready to Unlock Your Enterprise's Full Potential?