需求:
当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)