Jenkins增加钉钉通知

一.简介

钉钉(DingTalk )是阿里巴巴集团开发的企业协同办公软件。本节介绍jenkins与钉钉的集成。原理很简单,就是在钉钉群中增加一个钉钉机器人,我们将消息发送到钉钉机器人的API就可以了。

二.具体步骤

1.创建钉钉群,管理界面添加机器人
file

2.选择自定义方式
file

3.复制好webhook
file

4.选择关键字,这里配置后,消息里有发布这个词才能生效
file

5.在jenkins服务器上配置脚本/jen_script/dingding.py,这里钉钉用markdown语法写内容

#!/usr/local/python-3.6/bin/python3.6
import json,requests,sys,time,datetime

#[工程名、分支号、是否成功、编号]
job = sys.argv[1]
branch = sys.argv[2]
stat = sys.argv[3]
bianhao = sys.argv[4]

if int(stat) == 0:
    name = '发布成功!'
    tupian = '![file](https://prod-private.oss-cn-beijing.aliyuncs.com/yw/QQ%E6%88%AA%E5%9B%BE20201109153327.png)'
elif int(stat) == 1:
    name = '发布失败!'
    tupian = '![file](https://prod-private.oss-cn-beijing.aliyuncs.com/yw/QQ%E6%88%AA%E5%9B%BE20201109163201.png)'

url = "https://oapi.dingtalk.com/robot/send?access_token=022d90fsadaplfs8fgjsc4dc4c86cdf4ed666"
title = job + name
nowtime = datetime.datetime.now()
nowtime = str(nowtime.strftime('%Y-%m-%d %H:%M:%S'))
msg = """### %s \n
> 时间: %s \n
> 分支: %s \n
> 编号: #%s \n
> 地址: [工程链接](http://10.0.9.115:8080/job/%s) \n
%s
"""

def Alert():
    headers = {"Content-Type": "application/json"}
    data = {"msgtype": "markdown",
        "markdown": {
            "title": title,
            "text": msg %(title, nowtime, branch, bianhao, job, tupian)
        }
    }

    r = requests.post(url, data=json.dumps(data), headers=headers, verify=False)
    print(r.text)
Alert()

6.在OSS的prod-private的ubcket中,yw文件夹存储着构建时通知的图片
file

图片放到这里,可以拿去用,都是同大小的
成功:
file

失败:
file

7.编写pipeline配置

pipeline {
    agent any
    options {
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }
    environment {
        workspace = pwd()
        release_branch = 'master'
    }
    post { //直接复制这段到pipeline阶段内
        success {
            sh "/script/dingding.py ${JOB_NAME} ${release_branch} 0 ${BUILD_NUMBER}"
        }
        failure {
            sh "/script/dingding.py ${JOB_NAME} ${release_branch} 1 ${BUILD_NUMBER}"
        }
    }

8.发一版试一下
file

0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论