Create Jenkins Shared Library
In this article, we are going to learn how to create shared library in Jenkins. A shared library in Jenkins is a collection of Groovy scripts that are shared by several Jenkins jobs. The scripts are loaded into a Jenkinsfile before being executed. Shared libraries are used by developers to avoid rewriting the same code for many projects. Shared libraries allow code to be used between development projects, improving the software development life cycle. This significantly reduces coding time and aids in the avoidance of duplicate code.
Create a Shared Library Structure
First, we need to create a directory structure for our shared library. The directory structure is as follows:
|____vars |____src |____resources
Note: In this tutorial, we will be concentrating only on the vars folder for creating your first shared library. src and resources will be covered in the upcoming tutorials.
All of the files in the vars directory are global functions and variables. The function name is the name of the file.The filename will be used in our declarative process.
Creating a Shared Library
In our previous step we had created our library structure. Now you need to navigate to that vars directory. This is where we’ll store our shared library’s Groovy scripts. Create a new file called gitCheckout.groovy in the vars directory. The file should look like this:
1 |
|
Commit the changes and push it to your repository. Now we have created our first shared library. Now we need to configure our Jenkins to use this shared library.
Configure Jenkins to use the Shared Library
Now we have a basic git checkout library ready lets add it to Jenkins configurations.
- Name: shared-library-demo
- Default version: Specify a Git reference (branch or commit SHA), e.g. master
- Retrieval method: Modern SCM
- Source Code Management: Git
- Project repository: your GitHub repo url
Using the Shared Library in a Pipeline
Now we have created our shared library and configured Jenkins to use it. Now we can use it in our pipeline. Lets create a simple pipeline to test our shared library.
1 | 'shared-library-demo@master')_ ( |
Now we have created our pipeline. You can run it and see the results.
Conclusion
In this article, we learned how to create shared library in Jenkins. If you have any issue regarding this tutorial, mention your issue in the comment section or reach me through my E-mail.