Shared pipeline libraries in Jenkins

Updated: by Tom Donohue

Sometimes you might write some code that you want to reuse across several different pipelines in Jenkins. For example, you might write code to perform a deployment, or parse a file.

Once you start copying and pasting this same code into different pipelines, it can quickly become a bit of a maintenance headache. To avoid this, you can store your reusable functions in a Shared Library. You only need to write the code once, and then you can reference the same functions in all of your pipelines.

Setting up a shared library is fairly easy, and this post I’ll show you how.

  1. Create the shared library

    First you need to create a repository in your chosen source control management system, which will contain your library of functions.

    In your repository, create a directory called vars. This will hold your custom functions, e.g.:


    I’m using Git to store my repository. I’ve created a sample repo on GitHub, which includes one function, the sayHello example from the official Jenkins documentation.

    See the example repository on GitHub

  2. Add your custom functions

    Each custom function is just a different .groovy file in your vars/ directory. For example, a simple greeting function would look like this:

    #!/usr/bin/env groovy
    def call(String name = 'human') {
      echo "Hello, ${name}."
  3. Configure the library in Jenkins

    You can add a shared library dynamically from a Jenkinsfile, or you can configure the library using the Jenkins web console.

    To add your shared library (I’m using my demo on GitHub as an example):

    In Jenkins, go to Manage Jenkins → Configure System. Under Global Pipeline Libraries, add a library with the following settings:

    • Name: pipeline-library-demo
    • Default version: Specify a Git reference (branch or commit SHA), e.g. master
    • Retrieval method: Modern SCM
    • Select the Git type
    • Project repository:
  4. Use the library in a pipeline

    To use the shared library in a pipeline, you just add @Library('your-library-name') to the top of your pipeline definition, or Jenkinsfile. Then call your function by name, e.g. sayHello:

    stage('Demo') {
        echo 'Hello world'
        sayHello 'Dave'

    NOTE: The underscore (_) is not a typo! You need this underscore if the line immediately after the @Library statement is not an import statement.

    The result of the pipeline above will look something like this:

    Jenkins job output

Leave a Comment