gitlab-webhook实现本地自动同步脚本

需求:

当gitlab上有变动时,本地进行git pull 同步
gitlab本地自动同步.py脚本
# -*- encoding:utf-8 -*-

import datetime
import json
import subprocess
import requests
from flask import Flask, request, jsonify

## 获取当前时间戳
LOCAL_TIME = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
## git_webhook_secret
github_secret = "c762e21ce0c4e11f6684ecbff93ef79bbea74f10"
## 钉钉机器人接口token
web_token="43a650d90211d839de6767218f5302e9361416f2c6a3294cc51efa44b2c9af8e"

app = Flask(__name__)

def push_ding(text):
    """
    发送钉钉告警信息
    主题中需包含钉钉关键字信息
    """
    msg = """主题: BJWAXXX服务器git同步执行结果
• 时间:{}
• 状态:Faild
• 结果:
  •  {}""".format( LOCAL_TIME, text)
    header = {
        "Content-Type": "application/json;charset=UTF-8"
    }
    data_info = {
        "msgtype": "text",
        "text": {
            "content": msg
        },
        "isAtAll": True
    }
    send_data = json.dumps(data_info)
    ChatBot = requests.post(url="https://oapi.dingtalk.com/robot/send?access_token={}".format(web_token), data=send_data, headers=header)
    opener = ChatBot.json()
    print(opener)
    if opener["errmsg"] == "ok":
        print(u"%s 通知消息发送成功!" % opener)
    else:
        print(u"通知消息发送失败,原因:{}".format(opener))


@app.route('/hook', methods=['POST'])
def post_data():
    """
    gitla回调接口,本地执行git pull命令
    """
    signature = request.headers.get('X-Gitlab-Token', '').split(':')[-1]
    print("signature:",signature)
    if signature != github_secret:
        text="token认证无效"
        push_ding(text)
        return "{}".format(text), 401
    retcode = subprocess.call("cd /root/yanwen/ && git pull", shell=True)
    if retcode == 0:
        return jsonify({'status': 'success'}), 200
    else:
        text="git pull error"
        push_ding(text)
        return jsonify({'status': "{}".format(text)}), 503

if __name__ == '__main__':
    app.run(host='10.10.10.10',port=8989)

posted @   咖啡馆  阅读(304)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示