2018-11-20 COSTIN MORARIU

If you’re a Jenkins user adopting Jenkins pipelines, it is likely that you have run in to the scenario where you want to break out common functionality from your pipeline scripts, instead of having to duplicate it in multiple pipeline definitions. To cater for this scenario, Jenkins provides the Pipeline Shared Groovy Libraries plugin.
You can configure your shared global libraries through the Jenkins UI (Manage Jenkins > Configure System), which is what most resource online seems to suggest. But if you are like me and looking to automate things, you do not want configure your shared global libraries through the UI but rather doing it programmatically. This post aims to describe how to automate the configuration of your shared global libraries.
Jenkins stores plugin configuration in its home directory as XML files. The expected configuration file name for the Shared Groovy Libraries plugin (version 2.8) is: org.jenkinsci.plugins.workflow.libs.GlobalLibraries.xml
Here’s an example configuration to add an implicitly loaded global library, checked out from a particular Git repository:
<?xml version=’1.0′ encoding=’UTF-8’?> <org.jenkinsci.plugins.workflow.libs.GlobalLibraries plugin=”workflow-cps-global-lib@2.8″> <libraries> <org.jenkinsci.plugins.workflow.libs.LibraryConfiguration> <name>my-shared-library</name> <retriever class=”org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever”> <scm class=”jenkins.plugins.git.GitSCMSource” plugin=”git@3.4.1″> <id>7356ba0d-a25f-4f61-8c56-b3c565a39929</id> <remote>ssh://git@github.com:Diabol/jenkins-pipeline-shared-library-template.git</remote> <credentialsId>ssh</credentialsId> <traits> <jenkins.plugins.git.traits.BranchDiscoveryTrait/> </traits> </scm> </retriever> <defaultVersion>master</defaultVersion> <implicit>true</implicit> <allowVersionOverride>true</allowVersionOverride> </org.jenkinsci.plugins.workflow.libs.LibraryConfiguration> </libraries> </org.jenkinsci.plugins.workflow.libs.GlobalLibraries>
You can also find a copy/paste friendly version of the above configuration on GitHub: https://gist.github.com/tommysdk/e752486bf7e0eeec0ed3dd32e56f61a4
If your version control system requires authentication, e.g. ssh credentials, create those credentials and use the associated id’s in your org.jenkinsci.plugins.workflow.libs.GlobalLibraries.xml
.
Store the XML configuration file in your Jenkins home directory (echo “$JENKINS_HOME”
) and start your Jenkins master for it to load the configuration.
If you are running Jenkins with Docker, adding the configuration is just a copy directive in your Dockerfile:
FROM jenkins:2.60.1
...
COPY org.jenkinsci.plugins.workflow.libs.GlobalLibraries.xml $JENKINS_HOME/org.jenkinsci.plugins.workflow.libs.GlobalLibraries.xml
Jenkins environment used: 2.60.1, Pipeline Shared Groovy Libraries plugin 2.8