Opscraft
Groovy for pipelines · Lesson 7 of 8 · 4 min read

Designing, testing and governing a shared library

The "standard pipeline" pattern

Teams' Jenkinsfiles shrink to a declaration of intent:

Enlarge diagramJenkinsfile (6 lines)standardPipeline(service:'orders', language: 'java')platform-libv2checkoutbuild + testscanimagedeploy stagingapprove → prod
Figure 1. The standard pipeline pattern: a team's Jenkinsfile states intent in a few lines; the library expands it into the full, tested pipeline.
Swipe sideways to see all of it, or tap to open it full screen.
@Library('platform-lib@v2') _
standardPipeline(
  service: 'orders',
  language: 'java',
  deploy: [envs: ['staging', 'prod']],
)
// vars/standardPipeline.groovy
def call(Map cfg) {
  def defaults = [language: 'java', runTests: true, scan: true, deploy: [envs: ['staging']]]
  cfg = defaults + cfg                                  // shallow merge; deep-merge nested maps if needed
  if (!cfg.service) { error 'standardPipeline: service is required' }

  pipeline {
    agent { kubernetes { yaml libraryResource("org/acme/ci/pod-templates/${cfg.language}.yaml") } }
    options { timeout(time: 45, unit: 'MINUTES'); buildDiscarder(logRotator(numToKeepStr: '30')) }
    stages {
      stage('Test')  { when { expression { cfg.runTests } } steps { runTests(cfg) } }
      stage('Image') { steps { script { env.IMAGE = buildImage(name: cfg.service) } } }
      stage('Scan')  { when { expression { cfg.scan } } steps { scanImage(env.IMAGE) } }
      stage('Deploy staging') {
        when { branch 'main' }
        steps { gitopsPromote(service: cfg.service, env: 'staging', image: env.IMAGE) }
      }
    }
    post { failure { notify.failure(cfg.service) } }
  }
}

A whole declarative pipeline {} can live inside a vars step. Benefits: consistency, security gates enforced centrally, one place to improve build speed for 100 repos. Risks: a monolith that can't handle edge cases — offer extension points (hooks/closures, extraStages) and allow teams to compose lower-level steps when needed.

What belongs in a library

Good: standard build/test/scan/deploy steps, image tagging conventions, GitOps promotion, notifications, pod templates, quality gates. Bad: secrets (reference credential IDs only), a 2,000-line god-file, team-specific hacks, logic that should be a real tool (write a CLI and call it).

Testing

  • Unit tests with JenkinsPipelineUnit (or Spock): load a vars script, mock steps like sh, echo, libraryResource, and assert the call stack or behaviour.
class BuildImageTest extends BasePipelineTest {
  @Override @Before void setUp() {
    super.setUp()
    helper.registerAllowedMethod('container', [String, Closure]) { n, c -> c() }
    binding.setVariable('env', [GIT_COMMIT: 'abcdef1234'])
  }
  @Test void tagsWithShortSha() {
    def step = loadScript('vars/buildImage.groovy')
    def img = step.call(name: 'orders')
    assert img.endsWith('/orders:abcdef1')
  }
}
  • Integration tests: run a real Jenkins (Docker, JenkinsRule, or a staging controller) against test repos.
  • CI on the library repo runs tests and linting (npm-groovy-lint/CodeNarc) on every PR.
Enlarge diagramUnit testsJenkinsPipelineUnit:mock sh, assert callsLintCodeNarc /npm-groovy-lintIntegrationreal Jenkins againsttest reposPilot reposa few teams beforeeveryone
Figure 2. Testing a shared library, from fast to realistic.
Swipe sideways to see all of it, or tap to open it full screen.

Versioning and rollout

  • Semantic versioning with Git tags (v2.3.0). Major versions for breaking changes.
  • Teams pin a major or exact version (@Library('platform-lib@v2') via a moving v2 tag, or exact tags with Renovate bumps).
  • Breaking changes: changelog, deprecation warnings in the old version (echo 'WARNING: buildImage(registry:) is deprecated'), a migration window, and testing on a few pilot repos first.
  • Protect the repo: required reviews from the platform team, because a bad merge can break every pipeline at once — or, for a trusted library, compromise the controller.
Enlarge diagramTagsemver, e.g.v2.4.0Pilota few repos try itMove v2teams on @v2get itDeprecatewarnings in theold APIMajorv3 only forbreaking changes12345
Figure 3. Rolling out a library change used by many pipelines.
Swipe sideways to see all of it, or tap to open it full screen.