What are Jenkins Shared Libraries and why use them?
AdvancedConceptJenkins
Answer
A shared library is a Git repository of Groovy code that many Jenkinsfiles load, so common pipeline logic is written and fixed once. Layout: vars/ holds global steps (vars/buildImage.groovy becomes the step buildImage), src/ holds regular Groovy classes, resources/ holds static files loaded with libraryResource.
You configure it under Manage Jenkins > System > Global Pipeline Libraries (or at folder level), then load it with @Library('[email protected]') _. Pin to tags in production so a library change cannot break every pipeline at once.
// vars/buildImage.groovy
def call(Map cfg) {
sh "docker build -t ${cfg.name}:${cfg.tag} ."
sh "docker push ${cfg.name}:${cfg.tag}"
}
More on Jenkins
What is Jenkins and how is its architecture organised?BeginnerWhat are executors, nodes and labels in Jenkins?IntermediateWhy should you not run builds on the Jenkins controller?BeginnerHow do inbound (JNLP/WebSocket) and SSH agents connect to the controller?IntermediateWhat is a Jenkinsfile and where does it live?BeginnerDeclarative versus Scripted Pipeline: what are the differences?Intermediate