该篇文章实现了基于企业微信进行审批的功能(也支持其他的webhook)
前提是进行sharelibrary的配置
一、首先我们使用jenkins的sharelibrary进行审批人全局参数的设置(该步骤是为了当审批人变动时不需要该每个pipeline只改动全局变量即可)
二、我们将发送通知的函数也进行sharelibrary的全局函数设定
package org.devops
def HttpReq() {
sh returnStdout: true, script: """
set +x //该命令是sh的隐式输出,不会再jenkins中的控制台输出具体命令执行过程,防止用户在控制台看到token
python3.6 /opt/test.py ${adminUser} ${JOB_NAME} ${approveInfo} ${BUILD_ID} ${env.randomToken} ${BUILD_URL} > /dev/null
"""
}
test.py是发送通知的python脚本
import sys
import json
import requests
def send_json_to_webhook(json_data):
webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2f1ba5cd-8e7f-4897-ae05-518b83c7xxxxx' #替换成自己的
headers = {'Content-Type': 'application/json'}
try:
response = requests.post(webhook_url, data=json.dumps(json_data), headers=headers)
response.raise_for_status()
print('JSON data sent successfully')
except requests.exceptions.HTTPError as errh:
print('HTTP Error:', errh)
except requests.exceptions.ConnectionError as errc:
print('Error Connecting:', errc)
except requests.exceptions.Timeout as errt:
print('Timeout Error:', errt)
except requests.exceptions.RequestException as err:
print('Error:', err)
# 从命令行参数获取审批信息(可自行添加)
approval_message = {
"adminUser": sys.argv[1],
"application_name": sys.argv[2],
"build_info": sys.argv[3],
"build_number": sys.argv[4],
"verification_code": sys.argv[5],
"approval_link": sys.argv[6]
}
# 生成消息内容(内容可自定更改)
message_text = f"生产发布申请,请【{approval_message['adminUser']}】审批: {approval_message['adminUser']}\n- 应用名称:{approval_message['application_name']}\n-
构建信息:{approval_message['build_info']}\n- 构建序号:{approval_message['build_number']}\n- 随机验证码:{approval_message['verification_code']}\n- 审批链接: {ap
proval_message['approval_link']}"
# 创建对应的JSON数据
json_data = {
"msgtype": "text",
"text": {
"content": message_text
}
}
send_json_to_webhook(json_data)
三、进行流水线参数的配置
定义一个是否需要审批的选项
定义需要谁来审批
对该次审批的一个描述
四、具体的pipeline
#!groovy
@Library('jenkinslibrary@master') _ //引用配置的sharelibrary
def approval = new org.devops.HttpReq() //引用函数
//调用方法库文件
def adminUserlist
def skipRemainingStages = false //当前节点是否跳过
def input_message //提示语
def randomToken //发布秘钥
def skipadminUser = false
pipeline {
agent {
label "java_agent"
}
options {
timeout(time:1, unit:'HOURS') // 流水线超时设置为1H
}
environment {
randomToken = sh (script: "/bin/bash -c 'echo \$RANDOM'" , returnStdout: true).trim()
approve = "${approve}" //jenkins参数化构建定义审批人员名单
}
stages{
stage("发送审批通知"){
when {
expression { env.approve != 'NO' }
}
steps{
wrap([$class: 'BuildUser']) {
script {
//获取当前登录用户账户、姓名
Applier_id = "${env.BUILD_USER_ID}"
Applier_name = "${env.BUILD_USER}"
}
}
script{
//判断审批人(sharelibrary中的全局参数)
adminUserlist = userlist()
if ("$adminUser" != ""){
adminUser = "$adminUser"
//如果审批人为自己,则退出任务
if ("$Applier_id" == "$adminUser"){
echo '审批人不能为本人,任务已终止'
error '审批人不能为本人,任务已终止'
}
} else{
echo '审批人不能为空,任务已终止'
error '审批人不能为空,任务已终止'
}
if ("${adminUserlist}".contains("$adminUser")) {
env.approvalDD = "$adminUser"
input_message = "$Applier_name 申请发布生产"
echo "$input_message"
approval.HttpReq()
} else {
echo '审批人信息获取失败,任务已终止'
error '审批人信息获取失败,任务已终止'
}
}
}
}
stage("等待审批"){
when {
expression { env.approve != 'NO' }
}
steps{
script{
def isAbort = false //取消按钮
timeout(time:1, unit:'HOURS'){ //等待审批人审批,并通过timeout设置任务过期时间,防止任务永远挂起
try {
def token = input(
id: 'inputap', message: "$input_message", ok:"同意", submitter:"$adminUser", parameters: [
[$class: 'StringParameterDefinition',defaultValue: "", name: 'token',description: '请输入发布的秘钥' ]
])
if ( "${token}" == env.randomToken) {
echo '你的审批已通过,继续执行!'
} else {
echo '秘钥错误,任务已终止'
error '秘钥错误,任务已终止'
}
}catch(e) { // input false
throw e
}
}
}
}
}
stage('版本发布') {
steps{
script {
echo "版本发布"
}
}
}
}
post {
success {
script {
echo "success"
}
}
always {
script {
qyWechatNotification mentionedId: '', mentionedMobile: '', moreInfo: '', webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2f1ba5cd-8e7f-4897-ae05-518b83c727ea' //通过企业微信插件进行通知
}
}
aborted {
script {
echo "aborted"
}
}
}
}
五、具体效果