Jenkins Shared Library Tutorial For Beginners

enkins Shared Library Tutorial For Beginners

We are in an era of microservices where modern applications are split into individually deployable components. Jenkins with no doubt is one of the best open-source CI/CD tool for deploying microservices. As compared to a monolithic application, you will have many pipelines to deploy individual microservices.

With pipeline as code, we can code our entire CI/CD process. It is treated the same way we develop applications. You can version your pipeline code and perform all levels of testing before using it for any application deployments.

What is Jenkins Shared Library

When we say CI/CD as code, it should have modularity and reusability. And mainly it should follow the DRY principles. He is where Jenkins Shared Library comes in to play.

Jenkins Shared library is the concept of having a common pipeline code in the version control system that can be used by any number of pipelines just by referencing it. In fact, multiple teams can use the same library for their pipelines.

You can compare it with the common programming Library. In programming, we create individual libraries that can be used by anyone just by importing it into their code.

For example, if you have a ten java microservices pipelines, the maven build step will be duplicated in all the 10 pipelines. And whenever a new service gets added, you will copy and paste the pipeline code again. Also, let say you want to change some parameter in the maven build step, you will have to do it all the pipelines manually.

For the same scenario, we can write a shared library for maven build, and in all the pipelines we just have to refer the maven build library code. In the future for any maven changes, all you have to update it he shared library code. It will be applied to all the pipelines.

Getting Started With Shared Library

A shared library is a collection of groovy files (DSLs + Groovy). All the groovy files should be present it a git repo. In this example, we will be using Github as our git repo. https://github.com/devopscube/jenkins-shared-library. You can clone this repo to get the basic structure of the shared library.

Shared library repo has the following folder structure.

jenkins-shared-library
|____vars
|____src
|____resources
  1. vars: This directory holds all the global shared library code that can be called from a pipeline. It has all the library files with a .groovy extension. It also supports .txt files for the documentation of shared library code. For example, if you have a file named maven-build.groovy, you can have a help file named maven-groovy.txt. In this file, you can write the respective shared library function help documentation in markdown format.  The help file can be viewed from <your-jenkins-url>/pipeline-syntax/globals page. 
  2. src: It is a regular java source directory. It is added to the classpath during every script compilation. Here you can add custom groovy code to extend yous shared library code. Also, you can import existing Jenkins and plugins classes using an import statement. There will be scenarios where your groovy DSL’s will not be flexible enough to achieve some functionality. In this case, you can write custom groovy functions in src and call it in your shared library code.
  3. resources: All the non-groovy files required for your ur pipelines can be managed in this folder. One such example is, you might need a common JSON template to make an API call during the build. This JSON template can be stored in the resources folder and called can be called in the shared library using the libraryResource function.

Here is the list of articles in this shared library series

  1. How To Create Jenkins Shared Library For Pipelines

Check out all other Jenkins Tutorials from here – Jenkins Tutorials For Beginners

enkins Shared Library Tutorial For Beginners

How To Create Jenkins Shared Library For Pipelines

Jenkins Shared Library For Common Pipeline Functionality

In this tutorial, you will learn how to create a basic shared library and integrate it with Jenkins and a sample pipeline.

Note: If you want to learn the shared library basic concepts and use cases, please take a look at this article.

We will look into the following four things to get your hands dirty with the shared library.

  1. Create a Shared Library Structure
  2. Create Custom Shared Library Code
  3. Configure Shared Library In Jenkins Configuration
  4. Create Declarative Pipeline as Code With Shared Library.

Let looks at each one in detail.

Create a Shared Library Structure

Note: In this guide, we will be concentrating only on the vars folder for creating your first shared library. src and resources will be covered in the advanced shared library guide.

Jenkins shared library has the following structure. You can get the basic structure and code used in this article from Github -> Jenkins Shared Library Structure

jenkins-shared-library
|____vars
|____src
|____resources

All the files under vars are global functions and variables. The file name is the function name. We will be using the filename in our declarative pipeline.

Create Custom Shared Library Code

In this section, we will create the shared library code for Git Checkout functionality.

Generate Pipeline Syntax Using Snippet Generator:

You can create the code snippets that can be used in share library function using the Pipeline Syntax Generator available in Jenkins. This will make our life easier for creating custom library DSL. All the supported pipeline functionality can be generated from the snippet generator.

You can access the syntax generator from your Jenkins on /pipeline-syntax/ path. For example,

http://devopscube-jenkins.com:8080/pipeline-syntax/

Here is the screenshot which shows creating a git checkout pipeline snippet using the pipeline syntax generator.

Number 5 in the screenshot shows the generated snippet. Here is the properly formatted checkout snippet.

checkout([
    $class: 'GitSCM', 
    branches: [[name: '*/master']], 
    doGenerateSubmoduleConfigurations: false, 
    extensions: [], 
    submoduleCfg: [], 
    userRemoteConfigs: [[url: 'https://github.com/spring-projects/spring-petclinic.git']]
    ])

Create a Shared Library For Git Checkout

Lets convert the checkout snippet we generated in the above step to a shared library.

Create a file named gitCheckout.groovy under vars folder.

Here is our Git Checkout shared library code. We have removed all the empty checkout parameters which got generated by default.

def call(Map stageParams) {

    checkout([
        $class: 'GitSCM',
        branches: [[name:  stageParams.branch ]],
        userRemoteConfigs: [[ url: stageParams.url ]]
    ])
  }

Here is the code explanation,

  1. def call(Map stageParams) – A simple call function which accepts a Map as an argument. From the pipeline stage, we will pass multiple arguments which get passed as a map to the shared library.
  2. stageParams.branch – its the branch parameter which comes from the pipeline stage and we use stageParams to access that variable in the shared library.

Commit the changes and push it to your repository.

Add Github Shared Library Repo to Jenkins

Now that we have a basic git checkout library ready lets add it to Jenkins configurations.

Step 1: Go to Manage Jenkins –> Configure System

Step 2: Find the Global Pipeline Libraries section and add your repo details and configurations as shown below.

Add Github Shared Library Repo to Jenkins

Use Checkout Library in Declarative Pipeline

We always call the library using the filename under vars. In this case, gitCheckout is the filename created under vars. Here is how we call gitCheckout library from the pipeline or Jenkinsfile

stage('Git Checkout') {
    gitCheckout(
        branch: "master",
        url: "https://github.com/spring-projects/spring-petclinic.git"
    )
}

As you can see we are passing branch and url parameter to the Checkout function. Here is the full declarative pipeline code.

@Library('[email protected]') _

pipeline {
    agent any
    stages {
        stage('Git Checkout') {
            steps {
            gitCheckout(
                branch: "master",
                url: "https://github.com/spring-projects/spring-petclinic.git"
            )
            }
    }
    }
}

Like gitCheckout, you can create all your pipeline steps a shared library and you don’t have to repeat your common functionalities in all your pipelines.

Jenkins Shared Library For Common Pipeline Functionality