Shared Libraries

Shared libraries let you reuse pipeline code across many projects instead of copying it into every Jenkinsfile.

Syntax@Library('my-shared-lib') _

As you build more pipelines you notice the same code repeated everywhere. A Shared Library is a separate Git repository of reusable pipeline code that any Jenkinsfile can call.

Structure

A shared library follows a fixed layout:

  • vars/ — global functions/steps callable by name (e.g. vars/deploy.groovy becomes a deploy() step).
  • src/ — Groovy classes for more complex logic.
  • resources/ — non-Groovy files like templates.

Using it

Import the library with @Library('my-lib') at the top of a Jenkinsfile, then call its functions like built-in steps.

Example

Example · bash
// In the shared library repo: vars/buildApp.groovy
// def call(String name) {
//     sh "echo Building ${name}"
//     sh 'make build'
// }

// In your Jenkinsfile:
@Library('my-shared-lib') _

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                buildApp('my-service')   // calls the shared step
            }
        }
    }
}

When to use it

  • A DevOps team extracts the Docker build-and-push logic into a shared library so all 30 microservices use the same tested steps.
  • A compliance team enforces a mandatory security-scan step by including it in a shared library that every Jenkinsfile must import.
  • A platform team versions shared library releases with Git tags so projects can pin to a stable version and upgrade at their own pace.

More examples

Create a shared library global var

Defines a global variable step called dockerBuild in a shared library that any Jenkinsfile can call.

Example · groovy
// vars/dockerBuild.groovy  (in the shared library repo)
def call(String imageName, String tag = env.BUILD_NUMBER) {
  sh "docker build -t ${imageName}:${tag} ."
  sh "docker push ${imageName}:${tag}"
}

Import and use shared library

Imports version v2.1.0 of the shared library and calls the custom dockerBuild step from the Jenkinsfile.

Example · groovy
@Library('[email protected]') _

pipeline {
  agent any
  stages {
    stage('Build & Push') {
      steps {
        dockerBuild('myorg/myapp')
      }
    }
  }
}

Shared library with src class

Defines a reusable Slack utility class in the src/ directory of a shared library.

Example · groovy
// src/com/example/Slack.groovy
package com.example

class Slack implements Serializable {
  static void notify(script, String msg) {
    script.slackSend channel: '#builds', message: msg
  }
}

Discussion

  • Be the first to comment on this lesson.