What if you have multiple projects all having similar Jenkins file? (If not, you can follow this post to create one or more) Is there a way we can template this so can maintain this file in one place? Is there a way to get a generic Jenkins file?

Turns out there is. We need a Jenkins plugin Pipeline: Shared Groovy Library. With this plugin we can refer to a pipeline defined in a separate groovy library and run that on our local Kubernetes cluster.

Personally I ran into a problem with insufficient memory/CPU on the minikube cluster. If you ever have the same you can start minikube with more of both like this:

minikube stop
minikube delete
minikube start --cpus 2 --memory 4096 —-vm-driver virtualbox

Autocompletion in IntelliJ

Look at the code here to see how our pipeline library looks. The project is structured like this:

jenkins-ci
├── src
└── vars

Everything in the vars directory is picked up as groovy functions and can be referenced in our test projects Jenkins file. The names of the files are the function names you have to call so do not use a capital letter.

In the src directory we can define groovy helper functions. This will not be the focus of this post but can be a fully grown library.

A handy trick when developing these pipelines is to generate a gdsl file of your Jenkins project. Go to <your project> -> Pipeline Syntax -> IntelliJ IDEA GDSL. Copy this content in a pipeline.gdls file and setup a groovy SDK. Now we have autocompletion on all functions available in our Jenkins!

Make a generic Jenkinsfile

The pipeline we defined in an older post (see here) is pasted in the file javaApplicationPipeline.groovy. In this file we surround it with a basic call function. Now it can be called as we see in the next section.

#!/usr/bin/groovy

def call(config = [:]) {
...
}

Note that we defined the maven image as a variable of the config. The image to use can be defined in all projects using the library separately. In the JavaBuildConfig.groovy file we define a default for these variables.

class JavaBuildConfig {
    String mavenImage = 'maven:3.5-jdk-8'
}

Refer from our project

With our library in place we can remove the pipeline config out of our Jenkins file and refer to it as follows: (or checkout the code here)

@Library('jenkins-ci') _

javaApplicationPipeline([
        mavenImage: 'maven:3.3.9-jdk-8-alpine'
])

We see the maven image we wish to use in the build step.

We need to make Jenkins aware of our library. Go to Manage Jenkins -> Configure System and scroll to Global Pipeline Libraries. Add our library (with name jenkins-ci) and we’re good to go. Run the build and we see that our library is used.

Jenkins build output

Hopefully you can now create your own generic Jenkins file to manage your pipelines in one place. Happy building!