If you are tired of copying the same pipeline steps like a broken record this guide will show you how to stop the madness with Groovy based shared libraries for Jenkins. You will learn how to structure a repo, author small reusable steps, load the library in a Jenkinsfile, and ship versions that humans can actually rely on. Expect practical tips and a little sarcasm where warranted.
Create a Git repository and enable the shared library integration in the Jenkins global configuration. The Jenkinsfile that consumes the library must live in a branch or repo that Jenkins can reach. Remember credentials and permissions early or the build will sulk and refuse to cooperate.
Follow the expected repository layout so the pipeline loader behaves. At the root of your library repo create two folders named vars
and src
. Put simple global step wrappers in vars
and real Groovy classes in src
. This is the convention Jenkins expects so you do not get mysterious runtime errors at 2 a m.
// vars/notifySuccess.groovy
def call(Map args) {
echo "Notifying that job ${env.JOB_NAME} finished"
// call into helper classes in src when logic gets heavy
}
You can load the library with the @Library
annotation or via the global library configuration in Jenkins. A typical declarative pipeline will call the global vars as plain functions. For example use notifySuccess()
or buildApp()
inside your stages. Both declarative and scripted pipelines benefit from shared code but pick one style and keep it consistent.
// example Jenkinsfile
@Library('my-shared-lib@v1') _
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
buildApp()
}
}
}
stage('Notify') {
steps {
notifySuccess([channel: 'team-ci'])
}
}
}
}
Test your pipeline and library locally with a Jenkins sandbox or a pipeline runner. For the Groovy classes in src
add unit tests using Spock or JUnit. Testing on the developer workstation is less painful than deploying blind to a shared Jenkins server and watching chaos reign.
Publish releases using tags or stable branches so consumers can pin to a known good version. Keep a short changelog and update examples in the repo. If you force everyone to use master you will earn the ire of your teammates and a small mountain of support requests.
src
for heavy logic and for easier unit testing.Shared libraries turn pipeline as code into something sane when done right. Follow the layout, write tiny reusable steps, test before you push, and version your library. Do that and your Jenkins pipelines will be more reliable and less dramatic. If nothing else you will reduce the number of times someone asks you to fix a pipeline at 3 a m.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.