Shared libraries for pipelines you stop repeating

Jenkins CI/CD Course · lesson 13 of 15 · 5 min read

One git repo of Groovy turns forty near-identical Jenkinsfiles into forty calls to one reviewed step.

Open this lesson in the learning hub

Key points

  • A shared library is a git repository with vars/, src/ and resources/ at its root.
  • A file vars/buildJava.groovy with a call method becomes a step you invoke as buildJava().
  • src/ holds ordinary Groovy classes in package directories for logic that wants real types.
  • resources/ holds templates and scripts you load at run time with libraryResource.
  • Pin the version: @Library takes a branch, tag or commit, and a floating branch changes every build.
  • Globally configured libraries are trusted and run outside the Groovy sandbox, so review them like production code.

Example

// vars/buildJava.groovy in the shared library repo
def call(Map cfg = [:]) {
  String image = cfg.image ?: 'maven:3.9-eclipse-temurin-17'
  pipeline {
    agent { docker { image image; args '-v $HOME/.m2:/var/maven/.m2 -e MAVEN_CONFIG=/var/maven/.m2' } }
    stages {
      stage('Verify') { steps { sh 'mvn -B -ntp -Duser.home=/var/maven verify' } }
    }
    post { always { junit '**/target/surefire-reports/*.xml' } }
  }
}

// Jenkinsfile in each service repo, pinned to a tag
@Library('platform-pipelines@v3.2') _
buildJava(image: 'maven:3.9-eclipse-temurin-21')

Put repeated pipeline logic in vars/ and pin every consumer to a tag, because trusted library code runs unsandboxed.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Jenkins CI/CD Course course, and every lesson in it is listed on the Jenkins CI/CD Course contents page.