需求,在我的gitlab仓库kube-config代码仓库,如果匹配到configmap.yaml文件发生变化,就触发钩子,执行kubectl命令更新配置文件。
- gitlab配置webhooks
- python3代码
from flask import Flask, request, jsonify
import json
import hmac
import hashlib
import base64
import requests
import urllib
import time
import subprocess
app = Flask(__name__)
app.debug = True
def Shell_cmd(dev, job, zhixing):
shell_c = "sh ./b.sh {} {} {}".format(dev, job, zhixing)
Cmd_run = subprocess.run(shell_c,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.decode("utf-8")
return Cmd_run
def dingding(clientUser, conent):
secret = "SEC"
token = 'd3b5a'
timestamp = int(time.time() * 1000)
data = (str(timestamp) + '\n' + secret).encode('utf-8')
hmac_code = hmac.new(secret.encode('utf-8'), data, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
url = f'https://oapi.dingtalk.com/robot/send?access_token={token}×tamp={timestamp}&sign={sign}'
r = requests.post(url, json={
"at": {
"atUserIds": [
f"{clientUser}"
],
"atMobiles": [电话1,电话2], #@指定人
"isAtAll": "false"
},
"text": {
"content": f"{conent}"
},
"msgtype": "text"
})
# logger.error(f"dingding发送消息: {conent}, 发送结果: {r.text}")
print(r.text)
@app.route('/', methods=['post'])
def add_stu():
if not request.data: # 检测是否有数据
return ('fail')
student = request.data.decode('utf-8')
# 获取到POST过来的数据
student_json = json.loads(student)
# 把区获取到的数据转为JSON格式
dev_fenzhi = student_json["project"]["default_branch"]
#项目路径
xiangmu_name = student_json["commits"][0]["modified"]
for i in xiangmu_name:
app_head = i.split('/')
# print(app_head)
try:
#huise环境
if dev_fenzhi == "master" and app_head[1] == "app" and app_head[3] == "configmap.yaml":
Shell_cmd("huise",app_head[2],"configmap")
huise_message = "{}/{}\n huise 配置重载成功".format(app_head[2],app_head[3])
dingding(app_head[2],huise_message)
#test环境
if dev_fenzhi == "master" and app_head[0] == "app" and app_head[2] == "configmap.yaml":
#重新拉取配置
Shell_cmd("test",app_head[1],"configmap")
message = "{}/{}\n test 配置重载成功".format(app_head[1],app_head[2])
dingding(app_head[1],message)
except:
print("推送项目包含不在app内")
return jsonify(student_json)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8084)
- b.sh
#!/bin/sh
test_name_space=(
test1
test2
test3
dev1
)
huise_name_space=(
huise
huise3
)
Date=`date`
name_xiangmu=$2
xuanze_nei=$3
Git_pull(){
cd /home/lzx/gitlab_webhook/dtk-kubernetes-test
git pull
}
Apply_config_huise(){
Git_pull
cd /home/lzx/gitlab_webhook/dtk-kubernetes-test/z-huise/app/$name_xiangmu
for i in ${huise_name_space[@]}
do
kubectl apply -f configmap.yaml -n $i
if [ $? -eq 0 ]
then
echo "$Date $i $name_xiangmu Apply_config 发布成功 " >> /home/lzx/gitlab_webhook/huise_Apply_config.log
fi
done
}
Apply_config_test(){
Git_pull
cd /home/lzx/gitlab_webhook/dtk-kubernetes-test/app/$name_xiangmu
for i in ${test_name_space[@]}
do
kubectl apply -f configmap.yaml -n $i
if [ $? -eq 0 ]
then
echo "$Date $i $name_xiangmu Apply_config 发布成功 " >> /home/lzx/gitlab_webhook/test_Apply_config.log
fi
done
}
#Apply_deplyment(){
#Git_pull
#cd /home/lzx/gitlab_webhook/dtk-kubernetes-test/app/$name_xiangmu
#echo Apply_deplyment
#for i in $name_space
#do
#kubectl apply -f deployment.yaml -n $i
#done
#}
#Apply_svc(){
#Git_pull
#cd /home/lzx/gitlab_webhook/dtk-kubernetes-test/app/$name_xiangmu
#echo Apply_svc
#for i in $name_space
#do
#kubectl apply -f service.yaml -n $i
#done
#}
huise_dev(){
if [ $xuanze_nei == "configmap" ]
then
Apply_config_huise
fi
}
test_dev(){
if [ $xuanze_nei == "configmap" ]
then
Apply_config_test
fi
}
case $1 in
"huise")
huise_dev
;;
"test")
test_dev
;;
esac
- 当前路径