Re-using a declarative pipeline in multiple repositories via a Shared Library

Do you have an identical declarative pipeline used in multiple repositories and you find yourself updating these multiple Jenkinsfile copies every time you make a change?

Starting September 2017 Shared Libraries in Jenkins now support declarative pipelines. This means you can now load the same single source Jenkinsfile into different repositories. Here’s how to accomplish it.

Decide where you want to store the shared library, for example in a repository called “devops”.
Create a vars folder in this repository and in this folder create a .groovy file that will contain your declarative pipeline.

myPipeline.groovy

def call(body) {
    pipeline {
        // your pipeline code as-is
    }
}

Setup Jenkins to reference the shared library.

  • Navigate to Manage Jenkins > Configure System > Global Pipeline Libraries
  • Enter the name of the shared library, e.g. “myCustomSharedLibrary”
  • Retrieval method: Modern SCM
  • Source Code Management: GitHub
  • Select the repository where the shared library is at

Save your modifications.

Next, in the repository where you want to use this pipeline with, edit your Jenkinsfile to use the shared library:

Jenkinsfile

@Library("myCustomSharedLibrary") _
    myPipeline()

Be sure not to remove the _ character, it’s required!

Jenkins now knows to look at the vars folder in the repository you’ve defined, and loads the groovy file which calls the pipeline to be used in the job started by the Jenkinsfile that references it. Simple!

Here’s some reading material on this very topic:

Leave a Reply