How to build libraries for Jenkins pipelines
If you use Jenkins pipelines for automating your builds, Soon you realize you have to copy and past similar code between different pipelines. Wouldn't it be great to write it only once and use it as many times you want?!
In fact, it is possible and it’s more simple than what you might think. So let’s get started.
Building a simple library for shared functions
First, create an empty project and add it to a git repository. Then create a folder vars
inside the root directory of your project. Go to vars
the folder and create any file you want with .groovy
extension. For example, I created a file named hello.groovy
Inside this file write any functions you want. Below is an example that prints hello world.
def printHello() { sh 'echo "hello world from library"'}
That’s it!! You wrote a library and you are done. Just make sure to put push your changes to Jenkins server.
Using your library in the pipeline
Put this code on top of your pipeline
library identifier: 'repo-name@master', retriever: modernSCM(
[$class: 'GitSCMSource',
remote: 'yourReposiotryAddress',
credentialsId: 'my-private-key'])
Then in your code use it like this filename.functionName()
For the hello world example it would be like this
hello.printHello()
credentialsId
is not required if your repo is public.
See an example
I recently built a Jenkins library and made it public. You can check it out from here https://github.com/MobodidTech/jenkins-shared.git
It is a very simple library and I’m planning to add more features to it later but even this simple example can be helpful to you.
Conclusion
Of course, there are more into writing a good Jenkins library, And you may want to use more advanced features. I’m a coder playing with Jenkins and this file -> function
structure is all we needed for our team. If you need to do more check out the official documentation. https://jenkins.io/doc/book/pipeline/shared-libraries/
Don’t forget to share your ideas in the comment section below, If you like the articles Clap! Also, Follow Me to read my other articles as well.