Shared libraries for pipelines you stop repeating
One git repo of Groovy turns forty near-identical Jenkinsfiles into forty calls to one reviewed step.
Open this lesson in the learning hubKey points
- A shared library is a git repository with
vars/,src/andresources/at its root. - A file
vars/buildJava.groovywith acallmethod becomes a step you invoke asbuildJava(). src/holds ordinary Groovy classes in package directories for logic that wants real types.resources/holds templates and scripts you load at run time withlibraryResource.- Pin the version:
@Librarytakes 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.