Jenkins Shared Library for Build Notifications
This shared library provides an elegant way to integrate build notifications into your Jenkins pipelines with minimal code. It automatically includes relevant information like build status and commit messages, making it easier to track what's happening with your builds.
Jenkins Shared Library for Build Notifications
Introduction
Effective CI/CD pipelines require clear communication about build statuses. When a build starts, succeeds, or fails, the development team needs to know immediately. This is where the Jenkins Shared Library for Build Notifications comes in - a lightweight, customizable solution for sending build notifications directly to your team's Slack channels.
This shared library provides an elegant way to integrate build notifications into your Jenkins pipelines with minimal code. It automatically includes relevant information like build status and commit messages, making it easier to track what's happening with your builds and quickly identify the cause of any failures.
The Problem
When working with Jenkins pipelines, adding notification functionality often means:
- Duplicating notification code across multiple Jenkinsfiles
- Managing webhook URLs and credentials in each pipeline
- Creating consistent formatting for different notification types
- Handling commit message retrieval and formatting
This leads to code duplication, inconsistent notifications, and increased maintenance overhead. Additionally, while Jenkins has good Slack integration, Microsoft Teams integration is more challenging due to its different messaging format and handling of special characters.
The Solution
The Jenkins Shared Library for Build Notifications solves these problems by:
- Centralizing notification logic in a shared library
- Standardizing notification format across all pipelines
- Automatically including commit messages in notifications
- Color-coding notifications based on build status
- Aggregating changes across multiple failed builds
How It Works
The library consists of several components:
Core Components
notifyBuild.groovy
: Main entry point that determines notification color and content based on build statusgetAllChangeResults.groovy
: Collects change logs from the current and previous failed buildsgetChangeStringForBuild.groovy
: Formats commit messages for a specific buildnotifyTeams.groovy
: (Currently disabled by default) Template for Microsoft Teams notifications
Notification Types
The library supports three types of notifications, each with a distinct color and content:
Build Started (Yellow)
When a build starts, a yellow notification is sent with basic information about the job. No commit messages are included at this stage.
Build Success (Green)
When a build succeeds, a green notification is sent that includes the commit messages that were part of the build.
Build Failed (Red)
When a build fails, a red notification is sent that includes the commit messages, helping teams quickly identify what changes might have caused the failure.
Implementation Details
Change Log Collection
One of the most valuable features of this library is its ability to collect and format commit messages. The getChangeStringForBuild.groovy
file handles this:
@NonCPS def call(build, escape = false) { MAX_MSG_LEN = 60 echo "Gathering SCM changes" def changeLogSets = build.changeSets def changeString = "" for (int i = 0; i < changeLogSets.size(); i++) { def entries = changeLogSets[i].items for (int j = 0; j < entries.length; j++) { def entry = entries[j] def truncated_msg = entry.msg.take(MAX_MSG_LEN) if (entry.msg.length() > MAX_MSG_LEN) { truncated_msg += "..." } changeString += "-[@${entry.author.getFullName().toLowerCase()}][${entry.commitId.take(6)}]: ${truncated_msg} \n" if (escape == true) { changeString += '\\n' } } } if (!changeString) { changeString = "- No new changes \n" } return "${changeString}" }
This code:
- Retrieves all changes from the build
- Formats each commit with author, commit ID, and message
- Truncates long messages for readability
- Handles the case where there are no changes
Aggregating Failed Builds
Another powerful feature is the ability to aggregate changes across multiple failed builds. This helps teams understand what changes might have contributed to a failure, even if they weren't part of the current build:
@NonCPS def call(escape = false) { def result = getChangeStringForBuild(currentBuild, escape) def buildToCheck = currentBuild.getPreviousBuild() while (buildToCheck != null && buildToCheck.result != 'SUCCESS') { if (escape == true) { result += '\\n' . "\nBuild #${buildToCheck.number} [${buildToCheck.result}]\n" . '\\n' } else { result += "\nBuild #${buildToCheck.number} [${buildToCheck.result}]\n" } result += getChangeStringForBuild(buildToCheck, escape) buildToCheck = buildToCheck.previousBuild } return result }
Using the Library in Your Pipelines
Using this shared library in your Jenkins pipelines is straightforward:
- Configure the library in Jenkins under "Manage Jenkins" > "Configure System" > "Global Pipeline Libraries"
- Include the library in your Jenkinsfile:
@Library('build-notifications') _
- Send notifications at appropriate points in your pipeline:
node { try { // Send notification that build has started notifyBuild('STARTED') stage('Build') { // Your build steps here } stage('Test') { // Your test steps here } } catch (e) { // If there's an exception, mark the build as failed currentBuild.result = "FAILED" throw e } finally { // Always send a notification with the final build status notifyBuild(currentBuild.result) } }
Why Teams Integration is Disabled
Originally, this library was designed to support both Slack and Microsoft Teams notifications. However, Teams notifications are currently disabled in the default configuration.
While we developed a nice adaptive card template for Teams, we encountered consistent issues with special character escaping and structured message delivery. Unlike Slack, which provides a reliable built-in method for notifications, Teams integration required complex workarounds that proved to be unstable in production environments.
The primary issues we encountered with Teams notifications were:
-
Special Character Escaping: Teams requires careful escaping of special characters in JSON, which became problematic when including commit messages with various symbols.
-
Line Break Handling: Different line break formats (
\n
,\r\n
, etc.) were interpreted inconsistently. -
Message Size Limitations: Long commit histories would sometimes exceed Teams' message size limits.
-
Inconsistent Delivery: Messages would occasionally fail to deliver without clear error messages.
Lessons Learned
Developing this shared library taught us several valuable lessons:
-
Shared Libraries Reduce Duplication: Moving common functionality to a shared library significantly reduces code duplication and maintenance overhead.
-
Standardized Notifications Improve Communication: Having consistent, well-formatted notifications makes it easier for teams to quickly understand build statuses.
-
Platform Integration Challenges: Different communication platforms have different requirements and limitations. What works well for Slack might not work for Teams.
-
Commit History Context is Valuable: Including commit messages in build notifications provides important context that helps teams quickly understand what changes might have caused a build failure.
Conclusion
The Jenkins Shared Library for Build Notifications provides a simple, elegant solution for keeping your team informed about build statuses. By centralizing notification logic and standardizing notification format, it makes it easy to add comprehensive build notifications to all your Jenkins pipelines.
While the Teams integration is currently disabled due to technical challenges, the Slack integration works reliably and provides valuable information to development teams. The library is also designed to be easily extensible, so you can customize it to fit your specific needs or add support for other notification platforms.
If you're looking to improve communication around your CI/CD processes, this shared library is a great place to start.
Technologies Used
DevOps & Cloud
Other
Related Projects
macOS menubar AI Prompt Assistant
A practical utility that lives in your menubar and helps improve your interactions with AI services.
Terminal Multiplexers: tmux and GNU Screen
A comprehensive guide to terminal multiplexing with tmux and GNU Screen for efficient terminal workflows.
Have a project in mind?
Let's work together to bring your ideas to life. Our team of experts is ready to help you build something amazing.