Jenkins Shared Libraries

·

2 min read

INTRODUCTION

A Jenkins shared library is a library with code you share between Jenkins jobs. Developers use libraries to share code and avoid duplication.

You can also store the shared library in the GitHub repositories so that you can tag, version, and also get the raw codes.

ADVANTAGES

  • Standardization of pipelines

  • Reduce duplicate code. Developers use shared libraries to avoid writing the same code from scratch for multiple projects. Shared libraries share code across development projects, thus optimizing the software development life cycle

  • Easy on-boarding of new applications, projects or teams

  • One place to fix issues with the shared or common code

  • Code Maintenance

  • Reduce the risk of errors

  • Less disk space is used because the shared library code is not included in the executable programs

USAGE

Using a shared library generally requires the following 3 steps:

  • First, create a Groovy script(shared script) and add it to the Git repository(where your pipeline code is stored) by creating a vars folder in Git Repository

  • Then configure in Jenkins to add the shared library to Jenkins.By default Jenkins searches for shared libraries in mentioned GIT SCM repository for vars folder, so you need not mention the complete path

  • Configuring a Global Pipeline Library

  • Configuring a 'Modern SCM' for a Pipeline Library

  • Finally, import the shared library that needs to be used in our pipeline: @Library('your-shared-library'), so that the code in the shared library can be used.

  • NOTE:- You should not give a function name, but a groovy script name. Here file name is helloWorld.groovy and the function is def call()

  • Sample Example (git branch details in shared library)

  • No alt text provided for this image

    Script is stored with extension of .groovy.

    So, I have stored the file as genericCI.groovy

  • No alt text provided for this image

  • No alt text provided for this image

In this I have given the name “code_compile”, so in the Jenkins file, I will be calling my shared library from this name I have also mentioned the URL of gitlab in which my code is kept & credentials of my repository.

As you can see, I have used Jenkinsfile in this I am calling my shared library from the name “code_compile”. Then in “stage clone” I am using the genericCI script for my pipeline

No alt text provided for this image

So consider a situation, if people have multiple Groovy script in the same repository. Then we can call a particular script by above groovyscriptname.functionname

Resources

https://www.linkedin.com/pulse/shared-library-jenkins-ishan-singh-parmar/

https://youtu.be/BLQ0PDjgN8w