How to Build a Custom DingTalk Notification with Jenkins Shared Libraries
This guide explains how to use Jenkins pipeline shared libraries to create a flexible DingTalk robot notifier, covering message types, template design, Groovy implementation, and integration into pipeline post‑steps for automated build alerts.
Jenkins enables extensive automation through pipeline shared libraries, which are code repositories automatically fetched and made available to pipelines. As DevOps practices grow, teams often need to push build results to communication tools; DingTalk is a popular choice in Chinese enterprises.
1. Requirement Overview
After a pipeline finishes, developers want to know why it ran, whether it succeeded, and other build details. Messaging can be done via email or chat tools, but chat tools like DingTalk provide faster feedback.
2. DingTalk Robot Basics
DingTalk group robots aggregate third‑party information (e.g., GitHub, GitLab, Trello, JIRA) into group chats. They support custom security settings (keywords, signatures, IP whitelist) to protect the token.
3. Existing Jenkins DingTalk Plugin A DingTalk plugin existed in Jenkins, with a 2.0 release in January 2020 that added more message types, but it does not support pipeline usage. 4. Implementing a Custom Notifier via Shared Library 4.1 Content Definition Application name Build result Current version (image tag) Build initiator Duration Build log link Change log (commit message, author, timestamp) 4.2 Shared Library Structure <code>(root) +- src # Groovy source files | +- org | +- foo | +- Bar.groovy +- vars | +- foo.groovy # global variable script | +- foo.txt # help file +- resources # external resources | +- org | +- foo | +- bar.json </code> The src directory follows standard Java layout and is added to the classpath during pipeline execution. The vars directory holds globally accessible Groovy scripts. 4.3 Core Implementation In src/org/devops/dingmes.groovy we define two methods: getChangeString() extracts currentBuild.changeSets to build a concise markdown list of commits, truncating messages to 20 characters and formatting timestamps. HttpReq(AppName, ImageTag, Status, CatchInfo) builds the JSON payload for DingTalk’s markdown message, wraps the call with wrap([$class: 'BuildUser']) to capture the build user, and sends the request using the httpRequest step. <code>def getChangeString() { def changeString = "" def MAX_MSG_LEN = 20 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] def truncatedMsg = entry.msg.take(MAX_MSG_LEN) def commitTime = new Date(entry.timestamp).format("yyyy-MM-dd HH:mm:ss") changeString += " - ${truncatedMsg} [${entry.author} ${commitTime}]\n" } } if (!changeString) { changeString = " - No new changes" } return changeString } def HttpReq(AppName, ImageTag=' ', Status, CatchInfo=' ') { wrap([$class: 'BuildUser']) { def DingTalkHook = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN" def ChangeLog = getChangeString() def ReqBody = """{ \"msgtype\": \"markdown\", \"markdown\": { \"title\": \"项目构建信息\", \"text\": \"### 构建信息\n>- 应用名称: **${AppName}**\n- 构建结果: **${Status} ${CatchInfo}**\n- 当前版本: **${ImageTag}**\n- 构建发起: **${env.BUILD_USER}**\n- 持续时间: **${currentBuild.durationString}**\n- 构建日志: [点击查看详情](${env.BUILD_URL}console)\n#### 更新记录:\n${ChangeLog}\" }, \"at\": {\"atMobiles\": [\"155xxxx5533\"], \"isAtAll\": false} }""" httpRequest acceptType: 'APPLICATION_JSON_UTF8', contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', ignoreSslErrors: true, requestBody: ReqBody, url: DingTalkHook, quiet: true } } </code> 4.4 Using the Notifier in Pipelines Call the method in the post block to send different messages for success, failure, unstable, or aborted builds: <code>post { success { script { dingmes.HttpReq(AppName, ImageTag, "构建成功 ✅") } } failure { script { dingmes.HttpReq(AppName, ImageTag, "构建失败 ❌", CatchInfo) } } unstable { script { dingmes.HttpReq(AppName, ImageTag, "构建失败 ❌", "不稳定异常") } } aborted { script { dingmes.HttpReq(AppName, ImageTag, "构建失败 ❌", "暂停或中断") } } } </code> 5. Result When a pipeline runs, DingTalk receives a markdown message containing all defined fields and a formatted change log, providing developers with immediate, readable build feedback. 6. Summary By leveraging Jenkins shared libraries, a custom DingTalk notifier can be built without writing a dedicated plugin, offering flexibility for any chat‑tool integration (e.g., WeChat Work, Feishu) by adapting the JSON payload.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack DevOps & Kubernetes
Focused on sharing DevOps, Kubernetes, Linux, Docker, Istio, microservices, Spring Cloud, Python, Go, databases, Nginx, Tomcat, cloud computing, and related technologies.
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.
