Loading

Quipoin Menu

Learn • Practice • Grow

jenkins / Shared Libraries
tutorial

Shared Libraries

When multiple pipelines share the same logic (e.g., building a Docker image, sending Slack notifications), you can extract that code into a Shared Library. Shared Libraries are Groovy scripts stored in a Git repository and loaded by Jenkins.

Why Shared Libraries?

  • DRY: Write once, use in many pipelines.
  • Versioned: Libraries are versioned (Git tags).
  • Encapsulate complex logic.
  • Reduce Jenkinsfile size and complexity.

Structure of a Shared Library

A shared library requires a specific directory structure in a Git repo:
(root)
├── vars/
│ └── myStep.groovy # defines a global variable/step
└── src/ # optional, for Java-like classes

Example: Create a Simple Step

In vars/sayHello.groovy:
def call(String name) {
echo "Hello, ${name}!"
}

Configuring the Shared Library in Jenkins

1. "Manage Jenkins" → "Configure System" → "Global Pipeline Libraries".
2. Add a library with a name (e.g., my-lib).
3. Set the Git repository URL and credentials.
4. Default version: can be a branch or tag (e.g., main).

Using the Shared Library in a Pipeline

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

pipeline {
agent any
stages {
stage('Hello') {
steps {
sayHello('Jenkins')
}
}
}
}

Loading Libraries from Same Repo

You can also load a library from the same SCM as your Jenkinsfile using library step:
library identifier: 'my-lib@main', retriever: modernSCM([
$class: 'GitSCMSource',
remote: 'https://github.com/org/my-lib.git',
credentialsId: 'github-token'
])

Best Practices

  • Version your library (use Git tags).
  • Keep steps small and focused.
  • Document each step.
  • Test library changes before rolling out.


Two Minute Drill
  • Shared Libraries reuse pipeline code across many jobs.
  • Structure: vars/ for global steps, src/ for classes.
  • Configure in "Global Pipeline Libraries".
  • Use @Library('name') _ to import.

Need more clarification?

Drop us an email at career@quipoinfotech.com