python - flask获取consul kv 操作k8s

2021-07-05
#coding=utf-8
from flask import Flask,request
import json,requests,os
import subprocess

app = Flask(__name__)
consul_server='consul.pro.yqn.corp'

path = '/opt/prometheus-rules/'
#path = '/tmp/'

def del_file(id):
    file= path + str(id) + '.yml'
    if os.path.exists(file):
        os.remove(file)
        return 'delete done'
    else:
        return 'no such file'

def get_consul(sid):
    import consul
    print(sid)
    c = consul.Consul(host=consul_server, port=8500, scheme='http')
    index, data = c.kv.get('prometheus/rules/%s.yml' %(sid))
    if data:
        file = path + str(sid) + '.yml'
        with open(file, 'w') as f:
            f.write(str(data['Value'], encoding="utf-8"))
            return 'update done'
    else:
        return 'no such yml rules'


@app.route('/prometheus', methods=['POST'])
def consul():
   print(request.method)
   data = request.get_data()
   data = json.loads(data)
   print(data)
   action = data.get('action')
   sid = data.get('id')
   if action == 'DISABLE' or action == 'DELETE':
      res=del_file(sid)
      subprocess.call("/opt/bin/prometheus/create-k8s-rule.sh DELETE %s" % (sid), shell=True)
   else:
      res=get_consul(sid)
      subprocess.call("/opt/bin/prometheus/create-k8s-rule.sh CREATE %s" % (sid), shell=True)
   return res

if __name__ == '__main__':
   app.run('0.0.0.0',5001)

标题:python - flask获取consul kv 操作k8s
地址:https://blog.njqhome.com:8443/articles/2021/07/05/1625474579093.html