Create a Jenkins Library
Create groovy files in a git repo under /vars/
The first step is to create a repository for your Jenkins library, if it’s made private, make sure Jenkins has access to it.
Before we populate the repo, let’s add it to Jenkins:
Manage Jenkins
–> Configure System
, find the Global Pipeline Libraries
section, click Add
.
The Name
can be anything, it’s what you’ll refer to in the Jenkins pipeline, the default version is the branch/tag you want to use by default. Everything else can be left default.
The structure of the repo will be:
repository
|-resources
|-src
|-vars
Essentially vars
are the functions you call within your pipeline, src are groovy source files you can use for more complex library functions, resources are static helper data for the src files.
For the sake of this we’ll just be focused on vars.
Take this simple function:
/*
Add paramsDescription() to a stage, and this will set the build description to the following format:
PARAMETER_KEY_1: PARAMETER_VALUE_1
PARAMETER_KEY_2: PARAMETER_VALUE_2
...
*/
def call() {
def paramsStringBuilder = new StringBuilder()
params.each { param ->
paramsStringBuilder.append("${param.key}: ${param.value}\n")
}
currentBuild.description = paramsStringBuilder.toString()
}
Let’s name it paramsDescription.groovy
and put it in the vars repo.
Once that is pushed, in order to use it in a pipeline, just add this to the top of your Jenkinsfile @Library('my-library') _
, my-library
being the name you specified earlier, you don’t need to do this if you set Load implicitly
to true
during setup.
You can also specify a specific branch/tag: @Library('wagensveld-jenkins@feature/branch') _
or @Library('wagensveld-jenkins@1.0') _