Groovy for pipelines · Lesson 6 of 8 · 3 min read
Shared libraries: structure and loading
Layout
jenkins-platform-lib/
├── vars/ # global variables = custom steps
│ ├── standardPipeline.groovy # → standardPipeline(...)
│ ├── buildImage.groovy # → buildImage(...)
│ ├── buildImage.txt # help text shown in Pipeline Syntax
│ └── notify.groovy
├── src/org/acme/ci/ # classes, normal Groovy packages
│ ├── ImageRef.groovy
│ └── Deployer.groovy
├── resources/org/acme/ci/ # non-Groovy files
│ ├── pod-templates/maven.yaml
│ └── scripts/smoke-test.sh
└── test/ # unit tests (JenkinsPipelineUnit / Spock)
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
vars/: custom steps
A file vars/buildImage.groovy defines a global variable buildImage. Its call method runs when you call it like a step:
// vars/buildImage.groovy
def call(Map cfg = [:]) {
def registry = cfg.registry ?: '123456789012.dkr.ecr.ap-south-1.amazonaws.com'
def tag = cfg.tag ?: env.GIT_COMMIT.take(7)
def image = "${registry}/${cfg.name}:${tag}"
container('kaniko') {
sh """/kaniko/executor --context ${cfg.context ?: '.'} \
--destination ${image} --cache=true"""
}
return image
}
def img = buildImage(name: 'orders')
A vars file can also expose several methods — notify.success(), notify.failure() — by defining plain methods instead of (or as well as) call.
src/: classes
// src/org/acme/ci/Deployer.groovy
package org.acme.ci
class Deployer implements Serializable {
def steps // the pipeline script, to call steps
Deployer(steps) { this.steps = steps }
def rollout(String ns, String deploy) {
steps.sh "kubectl -n ${ns} rollout status deploy/${deploy} --timeout=5m"
}
}
import org.acme.ci.Deployer
def d = new Deployer(this) // pass `this` so the class can call sh/echo
d.rollout('staging', 'orders')
Classes can't call steps directly — they need the script object passed in. Prefer vars/ steps for most work; use src/ for genuinely reusable logic and data types.
resources/
def podYaml = libraryResource 'org/acme/ci/pod-templates/maven.yaml'
writeFile file: 'smoke.sh', text: libraryResource('org/acme/ci/scripts/smoke-test.sh')
sh 'bash smoke.sh'
Loading a library
@Library('[email protected]') _ // static load at compile time; '_' is a placeholder import
@Library(['platform-lib@v2', 'security-lib']) _
library 'platform-lib@feature/new-scan' // dynamic load at runtime (step)
@versioncan be a tag (recommended for stability), branch, or commit SHA.- Admins can configure a default version and whether jobs may override it.
- Implicit libraries load automatically into every pipeline; explicit ones need
@Library. - Libraries are configured globally (Manage Jenkins / JCasC), per folder, or loaded ad hoc from SCM.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.