Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 40 ยท Scaling and Operating Jenkins

Shared Libraries

Share pipeline code across repositories with Jenkins shared libraries: vars and src layout, global steps, @Library versions, folder libraries and testing.

The first few Jenkinsfiles in a company are written by hand. By the fiftieth, they all contain the same 40 lines: check out, build the image, run the scan, notify Slack. Fix a bug in one and you must remember the other forty-nine. A shared library solves this. It is a Git repository of Groovy code that Jenkins loads into your pipelines, so common logic lives in one place, is versioned, and can be reviewed and tested like any other code.

This lesson shows the library layout, how to write a global step, how pipelines load a library at a specific version, how folder libraries differ, and how to test them. The library code is read-only Groovy. The runnable stand-in is a tiny library registry that resolves name@version and lets a "pipeline" call a library step.

One repo, many pipelines

Library repo Shared Groovy code in Git.
Jenkinsfiles Short and readable.
Versions Pin a tag or branch.

Fix once, every pipeline benefits.

1 / 2

The repository layout

A shared library is a normal Git repository with a fixed structure:

TEXT
my-pipeline-library/
โ”œโ”€โ”€ vars/
โ”‚   โ”œโ”€โ”€ buildApp.groovy        # becomes the step buildApp(...)
โ”‚   โ”œโ”€โ”€ buildApp.txt           # help text shown in the Pipeline Syntax pages
โ”‚   โ””โ”€โ”€ notifyTeam.groovy
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ org/example/
โ”‚       โ””โ”€โ”€ Version.groovy     # a plain Groovy class
โ””โ”€โ”€ resources/
    โ””โ”€โ”€ org/example/
        โ””โ”€โ”€ Dockerfile.template
  • vars/ holds global variables and steps. A file called buildApp.groovy is exposed to pipelines as buildApp. The usual pattern is a call method, which lets a pipeline use the name like a function.
  • src/ holds ordinary Groovy classes in packages, like a small Java project. Use it for logic that is easier to organize as classes (parsing, version calculation).
  • resources/ holds non-code files (templates, scripts, config) that a step reads with libraryResource.

Names in vars/ should be lowerCamelCase without dashes, because they become identifiers.

Writing a global step

Here is a step that wraps a common build routine:

GROOVY
// vars/buildApp.groovy
def call(Map config = [:]) {
  String buildImage = config.image ?: 'maven:3.9-eclipse-temurin-21'
  String goals = config.goals ?: 'verify'

  pipeline {
    agent { docker { image buildImage } }
    options { timeout(time: 30, unit: 'MINUTES') }
    stages {
      stage('Build') {
        steps { sh "mvn -B ${goals}" }
      }
    }
    post {
      always { junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml' }
    }
  }
}

The calling Jenkinsfile becomes tiny:

GROOVY
@Library('[email protected]') _

buildApp(goals: 'verify -Pintegration')

Passing a Map gives you named parameters with defaults. A step can also be a plain building block, without a whole pipeline, so it can be called inside steps or script:

GROOVY
// vars/notifyTeam.groovy
def call(String status, String channel = '#builds') {
  echo "Notify ${channel}: ${env.JOB_NAME} #${env.BUILD_NUMBER} is ${status}"
  // a real step would call the Slack plugin or an API here
}
GROOVY
post {
  failure { notifyTeam('FAILED', '#shop-team') }
}

Steps from vars/ run inside the pipeline's context, so they can call other pipeline steps (sh, echo, withCredentials). Classes in src/ are plain Groovy and need the pipeline context passed in explicitly:

GROOVY
// src/org/example/Version.groovy
package org.example

class Version implements Serializable {
  def steps
  Version(steps) { this.steps = steps }
  String shortCommit() {
    return steps.sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
  }
}

Implement Serializable on classes that live across steps, because pipelines can pause and resume (Scripted Pipeline and Groovy for Jenkins explains why).

Loading a library

There are three ways to use one:

  1. @Library('name@version') _ at the top of the Jenkinsfile. The underscore is a placeholder for the annotation target, a Groovy quirk you simply copy. Loading happens before the pipeline runs.
  2. Implicit loading: an administrator sets "Load implicitly" for a library, and every pipeline gets it with no annotation. Handy for a company standard, but it hides where steps come from.
  3. The library step for dynamic loads in a script, such as picking the version from a parameter:
GROOVY
library identifier: 'my-pipeline-library@main', retriever: modernSCM(
  [$class: 'GitSCMSource', remote: 'https://git.example.com/ci/pipeline-library.git'])

For classes in src/, import them after loading:

GROOVY
@Library('[email protected]') import org.example.Version

Where libraries are configured

An administrator defines libraries in Manage Jenkins > System > Global Trusted Pipeline Libraries: a name, a default version and how to fetch the repository. Libraries can also be defined on a folder (Folder > Configure > Pipeline Libraries), visible only to jobs in that folder. This is how a team can own its own library without affecting anyone else.

Trusted vs sandboxed

Global libraries are trusted: their code runs outside the Groovy sandbox and can call any Jenkins internals, so only administrators should be able to change them. Folder libraries run in the sandbox like ordinary pipeline code, so they can be maintained by the team but are limited to approved methods. Libraries loaded with the library step from an arbitrary repository are also sandboxed. Be careful who can push to a trusted library repository: that is as sensitive as administrator access (Security, Users and Authorization).

Versioning

The part after @ is a Git branch, tag or commit:

  • @main: always the newest code. Convenient, but a push to the library can break every pipeline at once.
  • @v1.4.0: a tag, stable and reproducible. Pipelines upgrade deliberately by changing the number.
  • @7f3a2c1: a commit hash, the strictest option.

Use tags for production pipelines, use semantic versioning (a major version bump when a step changes behavior incompatibly), and keep a changelog. If the administrator allowed it ("Allow default version to be overridden"), a Jenkinsfile can choose a version; otherwise it must use the configured default. A common safe pattern is to test a feature branch of the library from one pipeline with @my-feature-branch, then merge and tag.

The stand-in below mimics this: it holds library versions in a registry, resolves a name@version reference (falling back to a default version), and calls a step.

JS Stand-in: a mini shared-library registry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first run uses explicit steps from v1.4.0. The second omits the version, so the default is used. The third shows what happens when a pipeline pinned to an older tag calls a step that does not exist there: the same kind of error you would see after downgrading a library. The fourth fails fast because the requested version does not exist. Real Jenkins reports these as a library-resolution error or "No such DSL method" at the start of the build.

Testing a library

Library code can break many pipelines, so it deserves tests:

  • Unit tests with the community JenkinsPipelineUnit framework, a Java/Groovy test library that fakes the pipeline context so you can call a vars step and assert on the steps it made.
  • Integration tests: a small test repository with a Jenkinsfile that loads the library from the branch under review (@Library('my-pipeline-library@my-branch') _) and is built by a pipeline in CI.
  • Pure logic in src/ classes with ordinary Groovy tests, because classes that do not touch the pipeline context are easy to test.
  • Keep steps small, with clear inputs, so each does one job.

When not to share

Shared libraries are powerful and easy to overuse:

  • Don't hide everything in one giant buildApp with 40 options; a pipeline nobody can read in the Jenkinsfile is hard to debug. Share the repeated parts, keep the project-specific structure visible.
  • Version and document breaking changes, or you will be afraid to change the library.
  • Avoid heavy Groovy computation in steps; keep logic simple, and call scripts or tools for the heavy parts. Common Mistakes and Anti-Patterns lists more traps.
  • A library is code with your CI's privileges. Review it like production code.

What is real and what is the stand-in

The vars/src/resources layout, @Library, library, trusted versus sandboxed behavior and JenkinsPipelineUnit are real. The Groovy snippets are illustrative and are not executed on this page. The TryIt is a plain-JavaScript stand-in that models name and version resolution only; it does not load Groovy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file vars/deployApp.groovy with a call method is available in a pipeline as...?

    Files in vars/ become global variables or steps named after the file, and call() makes the name callable like a function.
  2. 2. Why use @Library('[email protected]') _ instead of @main?

    A branch like main moves, so a library change can break every pipeline at once. A tag is reproducible.
  3. 3. What is the main difference between global trusted libraries and folder libraries?

    Trusted global libraries need administrator control because they can call internals. Folder libraries are sandboxed like normal pipeline code.
  4. 4. Where would you put a Dockerfile template that a step needs to read?

    Non-code files go in resources/ and are loaded with the libraryResource step.
  5. 5. Which is a good way to test a library change before releasing it?

    Test branches through a test Jenkinsfile and automated tests, then tag a release.

Summary

  • A shared library is a Git repo with vars/ (global steps), src/ (classes) and resources/ (files).
  • Load it with @Library('name@version') _, implicitly, or dynamically with the library step.
  • Pin tags for stability; a branch like main moves under you.
  • Global libraries are trusted, folder libraries are sandboxed; protect write access.
  • Test libraries, keep steps focused and avoid hiding the whole pipeline behind one mega-step.

Next, make the controller itself reproducible with Jenkins Configuration as Code (JCasC).