Shared libraries

Jenkins · Advanced · 14 min

With many repositories, a shared library keeps pipelines short and lets one team fix the build logic everywhere.

A shared library is a Git repository with a fixed layout:

  • vars/: each name.groovy file defines a global step called name, implemented by its call(...) method. This is the most common part.
  • src/: Groovy classes in packages, imported normally.
  • resources/: non-Groovy files loaded with libraryResource.

Register the library under Manage Jenkins, System, Global Trusted Pipeline Libraries (or on a folder) with a name and a default version. A Jenkinsfile loads it with @Library('ci-lib@v2.1') _; the trailing underscore is an annotation target. With the default version configured as implicit, no annotation is needed at all.

A vars step can wrap a whole declarative pipeline, so an application's Jenkinsfile shrinks to standardJavaPipeline(deploy: true). Taking a Map of options keeps the call site readable and extensible.

Pin versions with tags in production and test library changes by pointing a single job at a branch. Libraries configured globally are trusted: they run outside the Groovy sandbox and can call any Jenkins API, so changes to them deserve the same review as changes to Jenkins itself. Folder-level libraries run in the sandbox.

Example

// ci-lib repository: vars/standardPipeline.groovy
def call(Map cfg = [:]) {
    pipeline {
        agent { docker { image "${cfg.image ?: 'maven:3.9-eclipse-temurin-21'}" } }
        stages {
            stage('Build') { steps { sh 'mvn -B verify' } }
            stage('Deploy') {
                when { expression { cfg.deploy && env.BRANCH_NAME == 'main' } }
                steps { sh "./deploy.sh ${cfg.app}" }
            }
        }
        post { always { junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml' } }
    }
}

// Application repository: Jenkinsfile (the whole file)
@Library('ci-lib@v2.1') _
standardPipeline(app: 'shop', deploy: true)

Remember

  • vars/name.groovy with call() becomes a pipeline step called name
  • Load with @Library('lib@version') _ and pin versions
  • Global libraries are trusted and bypass the sandbox; review them carefully

Watch out for

  • Loading libraries from a moving branch in production; one bad commit breaks every pipeline.

Check yourself

  1. A file vars/notify.groovy defines def call(String msg). How is it used in a Jenkinsfile?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.jenkins.io/doc/book/pipeline/shared-libraries/