Operations 6 min read

Send Jenkins Pipeline Alerts to DingTalk via a Shared Library – A Complete Guide

This guide walks you through installing the DingTalk and Build User Vars plugins, configuring a DingTalk robot, creating a Groovy shared library, and integrating it into a Jenkins pipeline to automatically push build notifications and change logs to DingTalk.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Send Jenkins Pipeline Alerts to DingTalk via a Shared Library – A Complete Guide

Why use DingTalk for Jenkins pipeline notifications

After a pipeline finishes, you may want to push a notification. DingTalk is chosen as the target, and the Jenkins build structure is used to send the messages.

Required plugins and environment

Jenkins 2.277.3 (installation guide in the previous article)

DingTalk plugin 2.4.3

Build User Vars plugin 1.7

:warning: Ensure your Jenkins version is >= 2.176.4

Configure the DingTalk robot

In Jenkins go to System Management → DingTalk and set up the robot as shown in the screenshot.

:warning: Manually enter the robot ID; do not let Jenkins generate it, otherwise it will change after a restart.

Install the Build User Vars plugin

After installation, restart Jenkins to activate the plugin.

Get the build user variable in a pipeline

wrap([$class: 'BuildUser']) { }

Create a shared library

Directory structure

$ tree jenkinslibrary
jenkinslibrary
├── README.md
└── src
    └── org
        └── devops
            └── dingmes.groovy

3 directories, 2 files

Groovy script (dingmes.groovy)

package org.devops

def GetChangeString() {
    MAX_MSG_LEN = 100
    def changeString = ""
    def changeLogSets = currentBuild.changeSets
    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]
            truncated_msg = entry.msg.take(MAX_MSG_LEN)
            commitTime = new Date(entry.timestamp).format("yyyy-MM-dd HH:mm:ss")
            changeString += "> - ${truncated_msg} [${entry.author} ${commitTime}]
"
        }
    }
    if (!changeString) {
        changeString = "> - No new changes"
    }
    return changeString
}

def DingdingReq(RobotID, Status) {
    wrap([$class: 'BuildUser']) {
        def changeString = GetChangeString()
        dingtalk(
            robot: RobotID,
            type: 'MARKDOWN',
            title: '你有新的消息,请注意查收',
            text: [
                "### 构建信息",
                "> - 应用名称:**${env.JOB_NAME}**",
                "> - 构建结果:**${Status}**",
                "> - 当前版本:**${env.BUILD_NUMBER}**",
                "> - 构建发起:**${env.BUILD_USER}**",
                "> - 持续时间:**${env.currentBuild.durationString}**",
                "> - 构建日志:[点击查看详情](${env.BUILD_URL}console)",
                "### 更新记录:",
                "${changeString}"
            ],
            at: ['xxxxxxxxxxx']
        )
    }
}
Replace xxxxxxxxxxx with the actual phone numbers of the DingTalk group members; multiple numbers can be added.

Configure the shared library in Jenkins

Navigate to System Management → Global Pipeline Libraries and add the library as shown in the screenshot.

Import the shared library in a pipeline

Use the following syntax to load the library: @Library('pipeline-library-demo')_ Example pipeline script:

#!groovy
@Library('pipeline-library-demo')_

def dingmes = new org.devops.dingmes()

String branchName = "master"
String gitlabCredentialsId = "xxx"
String gitUrl = "http://xxx/xxx/jenkinslibrary.git"
String robotId = "2e0e11c4-2211-4687-b317-cacf58197288"

pipeline {
    agent any
    stages {
        stage('Git Clone') {
            steps {
                git branch: "${branchName}", credentialsId: "${gitlabCredentialsId}", url: "${gitUrl}"
            }
        }
    }
    post {
        success {
            script { dingmes.DingdingReq(robotId, "构建成功 ✅") }
        }
        failure {
            script { dingmes.DingdingReq(robotId, "构建失败 ❌") }
        }
    }
}

After running, the build result and DingTalk notification look like the following screenshots.

Common issues

The variable currentBuild.durationString was not passed; initially wrapped it with withEnv.

The root cause was that Groovy does not support interpolation inside single‑quoted strings, so double quotes must be used.

Single‑quoted env.JOB_NAME fails to resolve, while double‑quoted works. Both single and double quotes resolve JOB_NAME itself.

Recommendation: use double quotes for all variables. Triple quotes behave the same way—''' does not support interpolation, but """ does.

Reference: https://www.ssgeek.com/post/jenkinssharelibrary-shi-jian-zhi-zi-ding-yi-tong-zhi-qi/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ci/cdPipelineGroovyShared LibraryJenkinsDingTalk
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.