How to Use Jenkins Shared Library

How to Use Jenkins Shared Library

Micro-service architecture is widely used in modern IT architecture. In practice, every service is a project and contains one Jenkins file. Therefore, the 90% logic of the Jenkins file is the same. This can generate duplicated code.

In this post, I am going to demonstrate how we can use Jenkins shared library to avoid duplicated code.

Prepare Gitlab for Jenkins Library

First, we need to prepare the Jenkins library that will be our shared library. Here is the sample library.

In the "vars" folder, we can use the file name as the function name in the Jenkins file later. There are four functions.

  • buildImage: build docker image

  • buildJar: build Jar file with maven

  • dockerLogin: login to Dockerhub

  • dockerPush: push the docker image to Dockerhub

Setup Shared Library in Jenkins

In Jenkins, go to Manage Jenkins -> Configure System and locate Global Pipeline Libraries, we put the Git URL and Credential that is defined in the previous post. And then we save it.

Use Shared Library

We will use this sample java maven app as a demo of how to use the defined Jenkins shared library.

In the Jenkins file, we declare the defined shared Jenkins library with the command "@Library('jenkins-shared-library')". Then we can load "script.groovy" which contains all the necessary commands we need.

#!/usr/bin/env groovy  
@Library('jenkins-shared-library')  
def gv
pipeline {  
    agent any
    tools {
        maven 'maven'    
    }
    stages {  
        stage("init") {  
            steps {  
                script {  
                    gv = load "script.groovy"  
                }  
            }  
        }  
        stage("build jar") {  
            steps {  
                script {  
                    buildJar()  // from library
                }  
            }  
        }  
        stage("build and push image") {  
            steps {  
                script {  
                    buildImage 'stevenchen521/demo-app:jma-3.0'  // from library with parameter
                    dockerLogin()
                    dockerPush 'stevenchen521/demo-app:jma-3.0'
                }  
            }  
        }  
        stage("deploy") {  
            steps {  
                script {  
                    echo "deploying"
                }  
            }  
        }  
    }  
}

We create a new multi-branch job called "java-maven-app" that refers to the repository sample java maven app. Then we run it and here is the result.

In the Dockerhub repository.

Summary

In this post, we demonstrated how to use the Jenkins shared library. We defined it as the global shared library in Jenkins. There is another way that we can "import" the library in Jenkins directly from the git repository. We will also show this part later.

Reference

Module 8 of DevOps Bootcamp