How to Create a Jenkins Shared Library Tutorial (Step by Step)

How to Create a Jenkins Shared Library Tutorial (Step by Step). If you would like to know about Jenkins servers then this post will help you how to create a Jenkins shared library post, how to load them and how to use them in the Jenkins pipeline. Let’s get started.

Before dive into creating a Jenkins library, we would like to give you some basic knowledge of Jenkins.

Jenkins is an open source and popular automation server that helps developers around the world to automate the software development process such as building, testing, and deploying. Jenkins is written in Java with plugins built for Continuous Integration purposes, which is a very important tool for DevOps. It achieves that with the help of plugins (Git, Maven 2). Jenkins server also provides continuous integration and continuous delivery of the software components. Jenkins main aim is accelerate the software development process through automation. This is a server based system that mainly runs on the servlet containers (the popular one is Apache servlet).

Jenkins SSO Plugin allows Single sign on (SSO) integration with ADFS, OKTA, Keycloak, Azure AD B2C, Salesforce, Oracle, IBM cloud, One Login, Auth0 and all SAML 2.0 identity providers.

Pros of Jenkins Server

  • It is an open source and free tool so easily accessible.
  • It is easy to install as it doesn’t require additional installations or components.
  • Developers can test and detect  errors of their codes as soon as they arise so helps with Continuous development and delivery.
  • Over 1000+ plugins to make your work easier and integrate with your development, testing and deployment  example GitHub/GitLab, Kubernetes).
  • Java built so is very flexible.
  • Jenkins is a continuous integration (CI) and continuous delivery (CD) tool.

What is Jenkins Shared Library?

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 are able to tag, version, and also get the raw codes.

Why do we need Jenkins Library?

Pros of Jenkins library

  • Copying and pasting the same code many times into  Jenkins pipeline is really a big issue. To avoid such a thing, we need the Jenkins library.
  • The Jenkins library helps in storing the reusable codes. So you need to write your code once, then you can share the same code (which you have built ) with different Jenkins pipelines.

Note: Is it possible to reuse the code in Jenkins?

Yes in order to customize the already written code, please follow the steps below:

  1. First, read the configuration File of the Jenkins pipeline.
  2. Then you need to perform a code review of the application (use the tool SonarQube).
  3. Perform some checks on the target environment.
  4. The final step is to perform a deployment.
  5. Then you can add these codes into a shared library, so that other projects can reuse them.
  6. Over a period, you can build a collection of the functions in your Jenkins library.

How to Create Jenkins Shared Library

In this section of  how to Create a Jenkins Shared Library, we are going to explain steps that are required to create the Jenkins shared library:

  1. First, you need to create the Groovy scripts -> then add them into your Git repositories.
  2. Then you can add your shared library into Jenkins from the “manage Jenkins screen”.
  3. Finally, you need to pull the shared library into the Jenkins library using the standard annotations which are available on the top of Jenkins(Files).

The shared library in the Jenkins looks like this:

				
					@Library('your-library-name')
				
			

What’s inside of the Jenkins library?

Once you created the shared library in the Jenkins, you will get to see two types of common code:

1. Steps

It is a collection of Global variables in the Jenkins terminology. But these are the “customized steps” that will be available to all the Jenkins pipelines.

For example, to deploy an application you might write a standard step then you review the code. To do this follow the navigation, add your customized codes into vars/YourStepName.groovy and then implement one more function that is def call function like this:

				
					#!/usr/bin/env groovy
// vars/YourStepName.groovy

def call() (){{
    // Do something here...
}
}

				
			

2. Other common codes

This might consist of helper classes or sometimes you want to include the common codes inside the pipelines. You can also use common code to store the static constraints which are used later throughout the pipeline.

The navigation to use the common codes, go to the file src/your/package/name in the directory and then you can use the groovy syntax.

For example, consider a common file xyz/tomd/GlobalVars.groovy (here you can notice the XYZ.tomd at the top).

				
					#!/usr/bin/env groovy  package 
    xyz.tomd

class GlobalVars {
    static String foo = "bar"
}
}

				
			

Then you can import this class file into the Jenkinsfile and also reference the variable like “GlobalVars.foo.“.

Create and use Jenkins Shared Library

Until now you have learned how to how to Create a Jenkins Shared Library. Now it’s time to learn how to create and use them in real time.

Create a Jenkins shared library

  1. First, you need to create a Git repository that consists of the library functions.
  2. Now you have your own Git repository, now create a directory called Vars. This directory holds all the custom steps.
  3. Each of these custom steps will be a part of the “Groovy” file underneath the “Vars” directory.

For example:

				
					vars/
    deployApplication.groovy
    parseFile.groovy
    sayHello.groovy
    readSystemCredentials.groovy
    doCodeReview.groovy
				
			

Adding your custom steps

Each of your steps is completely different inside the “groovy” file as well as in the “Vars/” directory. In Jenkins the variables are known as “Global variables” and located in the directory “Vars/”.

Now you have to create a file for your custom step and fill the below code:

				
					#!/usr/bin/env groovy

def call(String name = 'human') {
    echo "Hello, ${name}."
}

				
			

Notice that how Groovy script is implemented in the method “call”. After writing the above code custom codes within the braces {}. Also, you can add parameters for example name, and human.

Set up the library in Jenkins

Now you have a library which is created using custom steps, so need to connect this library with Jenkins. Follow the steps to perform this task:

  1. You have to define a shared library within a Jenkins file or you can configure the library by using the Jenkins web console.

Note: it’s always good to configure the shared library using the Jenkins web console so that you can share the library across all your build jobs.

2.  In Jenkins, go to manage Jenkins -> then select the configure system. Under the “Global pipeline libraries”, add the shared library with the following details:

  • Name : pipeline-library-demo
  • Default version: need to specify Git reference (for example branch or commit SHA).
  • Retrieval method: Modern SCM.
  • Now select the Git type.
  • Project repository: https://github.com/tutorialworks/pipeline-library-demo.git

Use the library in a Pipeline

To use the Shared library in the Jenkins pipeline add “@Library(‘your-library-name’)” to the aerial definitions or any Jenkins file.
Consider the below example:

				
					@Library('pipeline-library-demo')_

 stage(('Demo') {
     echo 'Hello world'
     sayHello 'Dave'
 }@
}
				
			

Here the “_” is not a type error, it’s mandatory to have an “_” if the line immediately after the @library annotation is not an import statement.

Suppose if you want to use the declarative sentence, follow the below syntax:

				
					libraries {{
     lib('pipeline-library-demo')
 }

 pipeline {
     // Your pipeline would go here....
 }
}
				
			

Jenkins shared library output

Now, run the above pipeline, the output should look like this:

Finally, you are done with the creation of the jerkins library.

How to Create a Jenkins Shared Library Tutorial (Step by Step) Conclusion

In this how to create a shared library in Jenkins post, we have explained how to set up the Jenkins server application, how to create the shared library, and how to connect the shared library to the Jenkins.

 

It’s important to have automation and streamlining the development process in today business. CI/CD is central to devops as it grows, scale the business and takes it to the next level.  

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x