Configuring and Using Jenkins Shared Libraries for Flexible Pipelines
This article introduces Jenkins shared libraries, explaining their structure, how to create a library with Groovy classes, configure it in Jenkins, and use it in pipelines, including sample code for colored log output and step-by-step setup instructions for DevOps practitioners.
Jenkins shared libraries allow reusable Groovy code to be packaged and referenced across pipelines, providing more flexible and powerful CI/CD workflows.
The article outlines three main parts: the library contents, how to create the library, and how to use it.
Library contents include a typical directory structure with docs/README.md , src/org/devops/tools.groovy , and vars folder, where src holds Groovy classes added to the classpath and vars holds script files exposed as global variables.
── docs
│ └── README.md
├── src
│ └── org
│ └── devops
│ └── tools.groovy
└── varsTo create a library, a new file src/org/devops/tools.groovy is added, defining a class with utility methods such as PrintMes(value, color) that prints colored messages using the AnsiColor plugin.
package org.devops
// formatted output
def PrintMes(value, color){
colors = ['red' : "\033[40;31m >>>>>${value}<<<<< \033[0m",
'blue' : "\033[47;34m ${value} \033[0m",
'green' : "[1;32m>>>>>${value}>>>>>[m",
'green1': "\033[40;32m >>>>>${value}<<<<< \033[0m"]
ansiColor('xterm') {
println(colors[color])
}
}In Jenkins global configuration, the shared library is added under “Global Pipeline Libraries” with a name (e.g., jenkinslib ) and a default branch (e.g., master ), pointing to the Git repository URL and credentials if the repo is private.
To use the library in a Jenkinsfile, the syntax @Library('jenkinslib') _ loads it, after which the class can be instantiated ( def tools = new org.devops.tools() ) and its methods called, for example tools.PrintMes("获取代码",'green') within pipeline stages.
#!groovy
@Library('jenkinslib') _
def tools = new org.devops.tools()
pipeline {
agent { node { label "master" } }
stages {
// Get code stage
stage("GetCode"){
steps{
timeout(time:5, unit:"MINUTES"){
script{
tools.PrintMes("获取代码",'green')
}
}
}
}
}
}The article concludes by encouraging readers to run the pipeline on their Jenkins instance to verify that colored log output appears.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.