在这篇文章中结合具体的示例来介绍在Jenkins中如何向钉钉推送消息。
这里使用Easypack的Jenkins 2.164.3来创建验证用的Jenkins环境。使用如下步骤即可完成。
事前准备docker和docker-compose,版本要求如下所示:
使用Easypack中准备好的LTS的Jenkins镜像,启动Jenkins。
命令:git clone https://github.com/liumiaocn/easypack.git
命令:
cd easypack/containers/alpine/jenkins
docker-compose up -d
liumiaocn:jenkins liumiao$ cat docker-compose.yml
version: '2'
services:
# jenkins service based on Jenkins LTS version
jenkins:
image: liumiaocn/jenkins:2.164.3centos7.7openjdk1.8
ports:
- "32002:8080"
- "50000:50000"
environment:
- JENKINS_ADMIN_ID=root
- JENKINS_ADMIN_PW=liumiaocn
- JENKINS_MODE=master
volumes:
- ./data/:/data/jenkins
- /var/run/docker.sock:/var/run/docker.sock
restart: "no"
liumiaocn:jenkins liumiao$
liumiaocn:jenkins liumiao$ docker-compose up -d
Creating network "jenkins_default" with the default driver
Creating jenkins_jenkins_1 ... done
liumiaocn:jenkins liumiao$ docker-compose ps
Name Command State Ports
--------------------------------------------------------------------------------------------------------------
jenkins_jenkins_1 /bin/tini -- /usr/local/bi ... Up 0.0.0.0:50000->50000/tcp, 0.0.0.0:32002->8080/tcp
liumiaocn:jenkins liumiao$
本文示例的Job将流水线分按照功能分为逻辑上的三段:构建(Build) 、测试(Test)、部署(Deploy),顺序如下所示。
创建一个名为test-dingtalk-notification的Pipeline类型的Job,具体Job内容如下:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Build stage ...'
}
}
stage('Test'){
steps {
sh 'echo Test stage ...'
}
}
stage('Deploy') {
steps {
sh 'echo Deploy stage ...'
}
}
}
}
Jenkins中有相关的插件,但是使用受限,而且目前也都已经不更新了
以上述的插件为例,由于明文将密码存在Jenkins的配置文件config.xml中作为CVE被爆出来但是一直没有对应。
插件方式本文不再详细验证,直接使用钉钉提供的API进行消息推送。
详细使用示例可参看:https://liumiaocn.blog.csdn.net/article/details/103753450
在本例中将使用此脚本进行消息推送。
在每个阶段添加消息推送,首先将上述脚本拷贝至Jenkins镜像的/usr/local/bin下并设置可以执行权限。
liumiaocn:chatops liumiao$ ls
dingtalk send_message.sh wechat
liumiaocn:chatops liumiao$ docker cp send_message.sh jenkins_jenkins_1:/usr/local/bin
liumiaocn:chatops liumiao$ docker exec -it jenkins_jenkins_1 sh
sh-4.2# which send_message.sh
which: no send_message.sh in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin)
sh-4.2# chmod 755 /usr/local/bin/send_message.sh
sh-4.2# which send_message.sh
/usr/local/bin/send_message.sh
sh-4.2# send_message.sh
usage: /usr/local/bin/send_message.sh TYPE TITLE CONTENT [URL]
TYPE: wechat|dingtalk
sh-4.2#
修改流水线代码,添加如下消息推送示例
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo Build stage ...'
sh 'export CHAT_WEBHOOK_KEY=your_owen_dingtalk_token_info; send_message.sh dingtalk "Build Stage" "Build Stage has been successfully completed..."'
}
}
stage('Test'){
steps {
sh 'echo Test stage ...'
sh 'export CHAT_WEBHOOK_KEY=your_owen_dingtalk_token_info; send_message.sh dingtalk "Test Stage" "Test Stage has been successfully completed..."'
}
}
stage('Deploy') {
steps {
sh 'echo Deploy stage ...'
sh 'export CHAT_WEBHOOK_KEY=your_owen_dingtalk_token_info; send_message.sh dingtalk "Deploy Stage" "Deploy Stage has been successfully completed..."'
}
}
}
}