Operations 10 min read

Master Jenkins Shared Libraries to Simplify CI/CD Pipelines

This guide explains why Jenkins Shared Libraries are essential for reducing repetitive pipeline code in micro‑service projects, walks through creating and configuring a shared library, and demonstrates advanced usage with parameters, multi‑branch pipelines, and environment variable handling.

Programmer DD
Programmer DD
Programmer DD
Master Jenkins Shared Libraries to Simplify CI/CD Pipelines

Introduction

In fast‑moving agile teams, accelerating software delivery is critical, and DevOps relies heavily on Jenkins as the core CI engine. Efficient use of Jenkins requires mastering Jenkinsfile, the text file that defines a pipeline.

What Is a Jenkinsfile?

A Jenkinsfile is the script that describes a Jenkins pipeline. It can be written in two styles:

Declarative Pipeline – starts with the pipeline keyword.

Scripted Pipeline – starts with the node keyword.

Jenkinsfile is a text file used to define a Jenkins pipeline and interact with Jenkins according to the defined steps.

Why Use a Jenkins Shared Library?

Micro‑service architectures split a monolith into many small services, each needing similar pipeline stages (Build, Test, Deploy). Writing the same steps in every Jenkinsfile leads to duplication. A shared library extracts common logic into reusable Groovy scripts, reducing repetitive code.

Creating a Jenkins Shared Library

Creating a shared library is straightforward:

Create a vars folder at the root of the repository.

Add a Groovy file with a custom name inside vars.

Define a call method in the Groovy file.

.
├── Jenkinsfile
├── README.md
└── vars
    ├── javaProjectCommonLibrary.groovy
    ├── javaProjectMultiBranchAndParamsCommonLibrary.groovy
    ├── javaProjectMultiParamsCommonLibrary.groovy
    ├── nodeProjectCommonLibrary.groovy
    └── pythonProjectCommonLibrary.groovy

1 directory, 7 files

Example of a simple shared library ( javaProjectCommonLibrary.groovy):

def call(String name = 'rgyb') {
    // Define a common step
    echo "Hello, ${name}."
}

Configuring the Shared Library in Jenkins

In Jenkins UI go to

Manage Jenkins → Configure System → Global Pipeline Libraries

and add the library name, then save.

Using the Shared Library in a Pipeline

Create a Pipeline job and add the following script:

@Library('first-shared-pipeline') _
javaProjectCommonLibrary 'rgyb rubbish'

For more complex scenarios, define a library that accepts a map of parameters:

def call(Map pipelineParams) {
    echo "Welcome, ${pipelineParams.name}."
    echo "Story: ${pipelineParams.storyName}."
}

Invoke it with:

@Library('first-shared-pipeline') _
javaProjectMultiParamsCommonLibrary(name: 'rubish rgyb', storyName: 'Hello World')

Advanced Shared Library with Multi‑Branch Support

Define a library that receives a closure to collect configuration:

def call(body) {
    def pipelineParams = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()
    // Echo collected parameters
    echo "${pipelineParams.NAME}"
    echo "${pipelineParams.STORY_NAME}"
    echo "${pipelineParams.VERSION}"
}

Use it in a Jenkinsfile:

@Library('second-shared-pipeline') _
javaProjectMultiBranchAndParamsCommonLibrary {
    NAME = 'rgyb rubbish'
    STORY_NAME = 'hello world'
    VERSION = '1.1.0'
}

Configure a Multibranch Pipeline job, point it to the repository and the shared library name ( second-shared-pipeline), and Jenkins will scan all branches.

Loading Variables into the Environment

To avoid repeatedly referencing pipelineParams, the library can load variables into the built‑in env object:

def call(body) {
    def pipelineParams = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()
    pipelineParams.each { k, v -> env."${k}" = v }
    pipeline {
        agent none
        stages {
            stage('Load Variables') { steps { script { /* variables already in env */ } } }
            stage('Build') { steps { echo "${BUILD_STAGE}" } }
            stage('Test') { steps { echo "${TEST_STAGE}" } }
            stage('Deploy') { steps { echo "${DEPLOY_STAGE}" } }
        }
    }
}

Then add the parameters in the Jenkinsfile:

@Library('second-shared-pipeline') _
javaProjectMultiBranchAndParamsCommonLibrary {
    NAME = 'rgyb rubbish'
    STORY_NAME = 'hello world'
    VERSION = '1.1.0'
    BUILD_STAGE = 'this is build stage'
    TEST_STAGE = 'this is test stage'
    DEPLOY_STAGE = 'this is deploy stage'
}

Conclusion

By creating and using Jenkins Shared Libraries, you can centralize common pipeline logic, support multi‑branch projects, and simplify parameter handling, ultimately reducing duplication and making CI/CD pipelines easier to maintain across teams.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DevOpsPipelineGroovyShared LibraryJenkins
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.