Introduction to Shared Libraries
Introduction to Shared Libraries
Overview
Jenkins shared libraries provide a powerful way to encapsulate reusable pipeline code and share it across multiple projects. This lesson covers the fundamentals of shared libraries, their architecture, and implementation patterns.
Library Architecture
Directory Structure
(root)
+- src/ # Groovy source files
| +- org/example/
| +- Utils.groovy # Utility classes
+- vars/ # Global variables/functions
| +- buildJava.groovy
| +- deployToKubernetes.groovy
+- resources/ # Non-Groovy files
| +- scripts/
| +- deploy.sh
+- tests/ # Test cases
+- org/example/
+- UtilsTest.groovy
Key Components
- src Directory
- Contains structured Groovy source files
- Follows standard Java package structure
- Houses reusable classes and utilities
- vars Directory
- Global variables and functions
- Each file creates a globally accessible object
- Provides pipeline step implementations
- resources Directory
- Static resources and helper scripts
- Configuration files and templates
- Shell scripts and other non-Groovy files
Implementation Guide
1. Basic Library Setup
// In Jenkins Configuration:
// Manage Jenkins > Configure System > Global Pipeline Libraries
// Library Configuration:
name: 'my-shared-library'
default version: 'main'
retrieval method: 'Modern SCM'
Git URL: 'https://github.com/organization/shared-library.git'
2. Creating Utility Classes
// src/org/example/Utils.groovy
package org.example
class Utils implements Serializable {
def script
Utils(script) {
this.script = script
}
def mvnBuild(String goals) {
script.sh "mvn -B ${goals}"
}
def notifySlack(String message) {
script.slackSend channel: '#builds',
color: 'good',
message: message
}
}
3. Implementing Global Variables
// vars/buildJava.groovy
def call(Map config) {
def utils = new org.example.Utils(this)
pipeline {
agent any
stages {
stage('Compile') {
steps {
utils.mvnBuild('compile')
}
}
stage('Test') {
steps {
utils.mvnBuild('test')
}
}
stage('Package') {
steps {
utils.mvnBuild('package')
}
}
}
post {
success {
utils.notifySlack("Build Successful: ${env.JOB_NAME} #${env.BUILD_NUMBER}")
}
}
}
}
Usage Examples
Basic Pipeline Usage
// Jenkinsfile
@Library('my-shared-library') _
buildJava()
Advanced Configuration
// Jenkinsfile with custom configuration
@Library('my-shared-library') _
buildJava(
mvnGoals: 'clean install',
jdkVersion: '11',
notifyChannel: '#team-builds'
)
Best Practices
- Code Organization
- Keep related functionality together
- Use meaningful package names
- Follow Groovy coding conventions
- Error Handling
// Example of robust error handling def call(Map config) { try { // Pipeline steps } catch (Exception e) { currentBuild.result = 'FAILURE' throw e } finally { // Cleanup steps } }
- Documentation
- Document all public methods
- Include usage examples
- Maintain changelog
- Testing
// tests/org/example/UtilsTest.groovy import org.example.Utils import org.junit.Test class UtilsTest { @Test void testMvnBuild() { def script = [sh: { cmd -> assert cmd == 'mvn -B compile' }] def utils = new Utils(script) utils.mvnBuild('compile') } }
Hands-on Exercise
Exercise 1: Create a Basic Shared Library
- Set up a Git repository for your shared library
- Create the basic directory structure
- Implement a simple utility class
- Create a global variable
- Test the library in a Jenkins pipeline
Exercise 2: Advanced Library Features
- Implement parameter validation
- Add error handling
- Create unit tests
- Document your code
- Set up version control
Additional Resources
- Jenkins Shared Libraries Official Documentation
- Pipeline Steps Reference
- Groovy Language Documentation
- Git Version Control Best Practices
Next Steps
- Explore custom step development
- Learn about global variables
- Master library versioning strategies