All guides

Jenkins shared libraries: one pipeline for many jobs

A Jenkins shared library is defined in an external source control repository and loaded into existing Pipelines. Each Jenkinsfile names the library and, after an @ sign, the version it wants.

A wall covered in coloured sticky notes

The directory structure

The Jenkins documentation gives this layout for a shared library repository:

Text

(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- Bar.groovy  # for org.foo.Bar class
+- vars
|   +- foo.groovy          # for global 'foo' variable
|   +- foo.txt             # help for 'foo' variable
+- resources               # resource files (external libraries only)
|   +- org
|       +- foo
|           +- bar.json    # static helper data for org.foo.Bar
  • vars hosts script files that are exposed as variables in Pipelines. The variable takes its name from the file. It must be all lowercase or camelCased to load properly.
  • src looks like a standard Java source directory. It is added to the classpath when Pipelines execute.
  • resources holds non-Groovy files. The libraryResource step loads one as a string.

The root's other directories are reserved for later enhancements.

A custom step with a call method

A file in vars that implements a call method can be invoked in a manner similar to a step. The documentation uses this example for a set of Pipelines that are mostly similar, the builds of Jenkins plugins:

Groovy

// vars/buildPlugin.groovy
def call(Map config) {
    node {
        git url: "https://github.com/jenkinsci/${config.name}-plugin.git"
        sh 'mvn install'
        mail to: '...', subject: "${config.name} plugin build", body: '...'
    }
}

With the library loaded as a global or folder-level library, the documentation's Jenkinsfile is a single line:

Groovy

buildPlugin name: 'git'

A call method can also hold a Declarative Pipeline. Three limits apply: the definition must be a whole pipeline, it must sit in vars/*.groovy, and it must be inside a call method. A single build can execute one Declarative Pipeline and no more.

The global library configuration

Go to Manage Jenkins, then System, then Global Trusted Pipeline Libraries. A library is defined with these settings:

  • A name. Scripts use it, so the documentation asks for a short identifier.
  • A source code retrieval method. The documentation recommends Modern SCM, which the Git and Subversion plugins support.
  • A default version, which is optional.
  • Load implicitly. Pipelines can then use the library's classes and global variables with no annotation.
  • Allow default version to be overridden. When it is enabled, a @Library annotation may override the default version.

Any folder can also have shared libraries. They are scoped to the Pipelines inside the folder or its subfolders.

The Library annotation and its version

These are the documented forms:

Groovy

@Library('my-shared-library') _
/* Using a version specifier, such as branch, tag, etc */
@Library('[email protected]') _
/* Accessing multiple libraries with one statement */
@Library(['my-shared-library', 'otherlib@abc1234']) _

For a library that only defines global variables, the symbol _ is annotated in place of an unnecessary import statement. Jenkins resolves and loads libraries while it compiles the script, which is before the script starts to run.

When a Pipeline references the library by name only, Jenkins uses the default version. If no default version is defined, the Pipeline must specify one. The library step loads a library dynamically during the build, and its version can be computed, for example from $BRANCH_NAME or a build parameter.

Versions as Git tags

The version can be anything the SCM understands. For Git, branches, tags and commit hashes all work. The documentation calls a tag a fixed version, in contrast to a branch. Tag each release of the library and name the tag in @Library.

Two documented features go with this. If a version is specified in the Jenkins configuration, scripts can be blocked from selecting a different one. A pull request to a library hosted on GitHub can be tested from a consumer Jenkinsfile with @Library('my-shared-library@pull/<your-pr-number>/head') _, when the library's SCM configuration uses GitHub.

Trusted and untrusted libraries

  • Trusted. Global libraries may be marked trusted. They may call any method in Java, in Groovy, in the Jenkins internal APIs, in Jenkins plugins and in third-party libraries. The source of the Pipeline: Groovy Libraries plugin describes them as running without sandbox restrictions. The documentation warns that anyone able to push commits to the library's repository could obtain unlimited access to Jenkins. Configuring these libraries requires the Overall/RunScripts permission.
  • Untrusted. A user who holds only the Overall/Manage permission can configure global libraries too, limited to untrusted ones. Those run in the Groovy sandbox, as typical Pipeline scripts do. The plugin's Messages.properties file labels that section Global Untrusted Pipeline Libraries. Folder-level libraries are always untrusted.

The sandbox only allows a subset of Groovy's methods. A script that uses a method outside that subset is halted until an administrator approves the method signature on the In-process Script Approval page. Because of the warning above, limit who can push to the repository of a trusted library.

Mistakes to avoid

  • State in global variables. The documentation says all global variables in a shared library should be stateless. State stored in one is lost when the Jenkins controller restarts.
  • Steps called from a class. A library class has no direct way to call a step such as sh or git. Pass the steps to the class explicitly with this.
  • Method calls outside a script block. In Declarative Pipeline, calling a method on an object is allowed only inside a script block. A call such as log.info goes inside a script directive.
  • Unsafe approvals. The script approval page says unsafe methods should not be enabled without considering the impact.
  • Replay on a trusted library. Replay lets you edit the source files of an untrusted library for one build. It is not supported for trusted libraries.
  • @Grab in a trusted library. The documentation says it has various issues and is not recommended.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides