jenkins pipeline 实现钉钉审批

jenkins pipeline 实现钉钉审批

一、需求

  1. Jenkins job 在构建任务时,推送一条审批消息。
  2. 点击消息确认与取消按钮进行审批。
  3. 根据审批结果触发继续构建还是取消构建。

二、流程图

在这里插入图片描述

三、实现效果

任务开始:

image-20230427140747776

image-20230427140835379

确认效果:

image-20230427141004877

拒绝效果

image-20230427141220071

image-20230427141758318

任务状态失败与取消后点击效果:

image-20230427141950656

image-20230427142048783

重复点击效果:

image-20230427142246003

四、pipeline脚本

pipeline {
    
    agent any 
    
    stages {
        stage('dingtask') {
            steps {
                script {
            		hook = registerWebhook(authToken: '123456')
            		webhookId = hook.url.substring(hook.url.lastIndexOf('/') + 1)
                		
                    dingtalk (
                        robot: '70e44955-d04b-4e65-b90c-f853c9f44ba4',
                        type: 'ACTION_CARD',
                        title: '确认发布',
                        text: [
                            '**是否确认发布**',
                            '',
                            '---',
                            "- 任务名称:${JOB_NAME}",
                            "- 构建ID:[#${env.BUILD_NUMBER}](${env.BUILD_URL})",
                            "- 构建人:${env.USER}",
                            "- 持续时长:${currentBuild.durationString}"
                        ],
                        btns: [
                            [
                                title: '确认',
                                actionUrl: "http://python脚本所在公网ip:8769/jenkins/webhook?url=${webhookId}&type=confirm&jobName=${JOB_NAME}&buildNumber=${env.BUILD_NUMBER}"
                            ],
                            [
                                title: '取消',
                                actionUrl: "http://python脚本所在公网ip:8769/jenkins/webhook?url=${webhookId}&type=cancel&jobName=${JOB_NAME}&buildNumber=${env.BUILD_NUMBER}"
                            ]
                        ]
                    )
                    
                    // 30秒没有确认 取消任务
                    timeout(time: 30, unit: 'SECONDS') {
                        data = waitForWebhook hook
                        // 解析 JSON 字符串
                        def json = new groovy.json.JsonSlurperClassic().parseText(data)
                        def type = json.type
                        // 判断 type 的值
                        if (type == 'cancel') {
                            echo "取消"
                            currentBuild.result = 'ABORTED'
                            error('任务被取消')
                        }
                    }
                }
            }
        }
        
        stage('test') {
            steps {
                echo '触发了~'
            }
        }
    }
}

脚本中使用到的 registerWebhook 方法 需要安装 Webhook Step Plugin 插件

在这里插入图片描述

五、python脚本

# -*- coding: utf-8 -*-

from flask import Flask, request
from jenkinsapi.jenkins import Jenkins
import requests

app = Flask(__name__)

@app.route('/jenkins/webhook', methods=['GET'])
def post():
    commitType = request.args.get('type')
    webhookId = request.args.get('url')
    jobName = request.args.get('jobName')
    buildNumber = request.args.get("buildNumber")

    # 创建Jenkins对象
    jenkins_url = 'http://jenkins ip:8080'
    username = 'admin'
    password = '123456'
    jenkins = Jenkins(jenkins_url, username, password)
    
    # 获取job对象
    job = jenkins.get_job(jobName)
    
    # 获取指定构建的信息
    build_number = int(buildNumber)
    build = job.get_build(build_number)
    build_result = build.get_status()

    # 打印构建状态
    print('Job "{}" build {} status: {}'.format(jobName, buildNumber, build_result))

    if build_result == 'ABORTED':
        return "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;color:orange;'>任务已中止,请重新构建<h1>"
    elif build_result == 'FAILURE':
        return "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;color:red;'>任务构建失败,请勿重复点击<h1>"

    # 组装webhook基础参数
    url = 'http://jenkins ip:8080/webhook-step/' + webhookId
    data = {'type': commitType}
    headers = {
        'Authorization': '123456',
        'Content-Type': 'application/json'
    }

    # 调用webhook
    try:
        response = requests.post(url, json=data, headers=headers)
        response.raise_for_status()
    except Exception as e:
        logging.exception("Failed to call Jenkins webhook step service.")
        return "请求失败:" + str(e)

    if commitType == 'confirm': 
        return "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;color: green;'>已同意</h1>" if response.status_code == 200 else "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;color:orange;'>请勿重复操作</h1>"
    else:
        return "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;;'>已拒绝</h1>" if response.status_code == 200 else "<h1 style='font-size: 2em;display: flex;justify-content: center;align-items: center;height: 100%;color:orange;'>请勿重复操作</h1>"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8769)
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值