Blog

Streamlining Pipeline Development with Shared Libraries in Jenkins

Evgeni Stoyanov
Evgeni Stoyanov
DevOps and Cloud Engineer
22.06.2023
Reading time: 5 mins.
Last Updated: 12.02.2024

Table of Contents

Maximizing Pipeline Efficiency with Jenkins Shared Libraries

In the CICD world, Jenkins emerges as one of the most prominent tools. It helps to automate building, testing, and deploying applications and infrastructure. One of Jenkins’ strengths is that it can use Shared Libraries, allowing DevOps engineers and developers to reuse code across multiple projects and pipelines. In this blog, we’ll explore the concept of Shared Libraries and discuss how they can improve your CICD workflows.

How to create a Shared Library in Jenkins?

Shared libraries are reusable blocks of code that can be shared between multiple pipelines. To create a shared library in Jenkins it is best to create a dedicated repository in your SCM tool where your code will be kept. You can use GitHub, GitLab, Bitbucket, etc. 

According to best practices, these repositories should be completely separate from the rest of your code, for example, if you have code with groovy pipelines, it should be in different repositories from the code for the Shared Libraries. Jenkins offers a dedicated section for configuring your Shared Library repositories and their credentials. Once these are configured, Jenkins can scoop and fill them into your pipelines. They are usually written in Groovy – an object-oriented language that is based on the Java platform.

Once you’ve created and configured the shared library, you can start using it in your pipelines. They are imported into pipelines with the `@Library` annotation. After which, in parentheses, you select the library. It’s common to import everything from the library, which is done by adding a space and an underscore after the brackets like this: @Library(“my-shared-library”) _

Alternatively you can import single class by importing it like so:

@Library('my-shared-library')
import mylib.ShareClass

It is recommended to keep libraries small in number of files and size, because every time you run a pipeline, the library is cloned into the workspace, which in the case of large libraries, can negatively affect the job runtime.

What are the benefits of Shared Libraries?

Let’s review the benefits of using Shared Libraries:

  • Code reuse: Shared Libraries allow for code reuse, reducing duplication and improving maintainability.
  • Standardization: With Shared Libraries, you can standardize your jobs by using steps that can be shared across multiple projects. This ensures consistency and reduces the possibility of errors.
  • Versioning and updates: Keeping functions/methods in a Shared Library repository allows easy updates while preserving information about previous versions of the code. This helps in managing changes effectively.
  • Collaboration between teams: Shared Libraries facilitate collaboration by enabling code sharing, reviewing, and collective improvements. It allows teams to work together more efficiently.

Step-by-Step Guide: Setting Up a Pipeline Using a Shared Library Function

Follow along with the step-by-step guide below to set up a pipeline using a function from share library.

  1. If we are going by the book we should create a new repository and then create a folder `vars` and a file with the code in this folder. In our case the file will be called myLibrary.groovy. Let’s define the function in this file:
def print(String name) {

    echo "Hello, ${name}!"

}
  1. Configure Jenkins so that it will be able to use the shared library.

Go to manage Jenkins. Configure System and scroll down to GLobal Pipeline Libraries. Click on Add and think of a name pertaining to the library. We chose my-shared-library for this article, but you can name it however you like. In the Default version section we will use the branch name, which in this case is main, but you can check the official Jenkins documentation for details about different version options.

  1. Add your newly created repository with the Shared Libraries and configure credentials to access this repository, then save the configuration. I suggest reading the documentation about the options in the Global Pipeline Libraries.
  2. Create Jenkins Pipeline

Now let’s proceed with the next stage – go ahead and create Jenkins Pipeline and name it according to the scenario and optionally add proper description.

For this test we can skip everything and leave it as default until we get to the pipeline section.

In the pipeline section generally, we can use “Pipeline script from SCM” such as GitHub or any other source control platform, but for now let’s paste the code directly into the pipeline by choosing “Pipeline script” for the sake of simplicity.

We will use the following code in our pipeline:

@Library(my-shared-library) _
pipeline {
agent any
stages {
     stage('Hello World') {
         steps {
             script {
                 myLibrary.print('John')
             }
         }
     }
}
}

As we mentioned before @Library(‘my-shared-library’) _ specifies that we want to load the shared library named ‘my-shared-library’ for this pipeline. The underscore _ indicates that we want to load all the default resources from the library.

In this blog we will skip the lines with pipeline, stages and agent as they are generic for Jenkins and not something specific pertaining to the Shared Libraries topic.

  1. The next thing we should discuss is in the script block. In the following line myLibrary.print(‘John’) we are invoking the `print` function from the file myLibrary in the library `my-shared-library` passing the string “John” as an argument.

Now we will run the job and see what happens:

Here is the second line in the Console Output:

Loading library my-shared-library@main

Then few lines below we can see the following:

Running on Jenkins in /apps/jenkins/workspace/OPERATIONS/shared-libraries-demo

[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello World)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Hello, John!
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

This means that the function “print” from our shared library works as expected.

Conclusion:

By following the step-by-step guide you have successfully configured your shared library, enabling code reuse and modularity in your Jenkins pipelines. With shared libraries you can now encapsulate common functionality, promote collaboration, and improve the maintainability of your Jenkins projects. By leveraging shared libraries, you can streamline your automation workflows, reduce duplication, and accelerate software delivery. So, dive into the world of shared libraries in Jenkins and unlock their full potential for your development team.

Unlock the Power of Shared Libraries in Jenkins for Streamlined Pipeline Development

Boost Efficiency and Collaboration with Our Experienced DevOps Company

One Response

  1. Quick tips:
    – Put your entire pipeline in the library. That way you don’t need CI/CD related commits in the app repo
    – This also makes it a lot lot easier to manage once a project has tens of branches where you need to implement a change

    Example:
    Jenkinsfile
    “`
    @Library(‘jenkins-shared-lib’) _

    ApplicationCI {
    runnerTemplate = “default.yaml”
    APP_NAME = “api-gateway”
    APP_CHANGESET = [ “api-gateway/”, “gradle/dependencies.gradle”, “build.gradle”, “settings.gradle” ]
    }
    “`

    Actual Pipeline Definition within vars/ApplicationCI.groovy:
    “`
    def call(body) {
    def pipelineParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()
    // v Functions located in the src folder of the library
    def funcs = new org.someOrg.Utilities()

    pipeline {
    // pipeline stuff
    }
    “`

Leave a Reply

Your email address will not be published. Required fields are marked *

More Posts

 This blog post will guide you through the creation of a Jenkins pipeline to automate AWS ECS (Elastic Container Service) and RDS (Relational Database Service) operations. The pipeline script is...
Reading
What is Renovate? Renovate is an automated dependency update service. It works by scanning private or public repositories and creates Merge Requests, based on the requirements we have and the...
Reading
Get In Touch
ITGix provides you with expert consultancy and tailored DevOps services to accelerate your business growth.
Newsletter for
Tech Experts
Join 12,000+ business leaders and engineers who receive blogs, e-Books, and case studies on emerging technology.