Skip to main content
Back to Lab Projects
Development Project

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.

Date: June 11, 2025
Read Time: 8 min
Tags:
jenkinsgroovyslackcicdnotificationsshared-library

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.

Slack Build Success Notification

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:

  1. Duplicating notification code across multiple Jenkinsfiles
  2. Managing webhook URLs and credentials in each pipeline
  3. Creating consistent formatting for different notification types
  4. 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:

  1. Centralizing notification logic in a shared library
  2. Standardizing notification format across all pipelines
  3. Automatically including commit messages in notifications
  4. Color-coding notifications based on build status
  5. 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 status
  • getAllChangeResults.groovy: Collects change logs from the current and previous failed builds
  • getChangeStringForBuild.groovy: Formats commit messages for a specific build
  • notifyTeams.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)

Slack Build Started Notification

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)

Slack Build Success Notification

When a build succeeds, a green notification is sent that includes the commit messages that were part of the build.

Build Failed (Red)

Slack Build Failed Notification

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:

  1. Retrieves all changes from the build
  2. Formats each commit with author, commit ID, and message
  3. Truncates long messages for readability
  4. 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:

  1. Configure the library in Jenkins under "Manage Jenkins" > "Configure System" > "Global Pipeline Libraries"
  2. Include the library in your Jenkinsfile: @Library('build-notifications') _
  3. 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:

  1. Special Character Escaping: Teams requires careful escaping of special characters in JSON, which became problematic when including commit messages with various symbols.

  2. Line Break Handling: Different line break formats (\n, \r\n, etc.) were interpreted inconsistently.

  3. Message Size Limitations: Long commit histories would sometimes exceed Teams' message size limits.

  4. Inconsistent Delivery: Messages would occasionally fail to deliver without clear error messages.

Lessons Learned

Developing this shared library taught us several valuable lessons:

  1. Shared Libraries Reduce Duplication: Moving common functionality to a shared library significantly reduces code duplication and maintenance overhead.

  2. Standardized Notifications Improve Communication: Having consistent, well-formatted notifications makes it easier for teams to quickly understand build statuses.

  3. Platform Integration Challenges: Different communication platforms have different requirements and limitations. What works well for Slack might not work for Teams.

  4. 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

🔹CI/CD

Other

🔹Jenkins
🔹Groovy
🔹Slack
🔹Microsoft Teams

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.