import json import time import requests import subprocess BOT_WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/78ae6e57-dd7b-4e51-83ac-37c30b632f9c' pendingDeleteClusters = [] def fetch_staging_clusters_json(): cmd = "KUBECONFIG=staging-infra-apiserver /usr/local/bin/kubectl get clusters -A -o json" inputDomain = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) jsonS = json.dumps(inputDomain.communicate()[0].decode('utf-8')) return json.loads(jsonS) def fetch_dev_clusters_json(): cmd = "KUBECONFIG=dev-infra-apiserver /usr/local/bin/kubectl get clusters -A -o json" inputDomain = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) jsonS = json.dumps(inputDomain.communicate()[0].decode('utf-8')) return json.loads(jsonS) def process_infra_clusters(): rawData = fetch_dev_clusters_json() clusters = json.loads(rawData) for cluster in clusters['items']: if 'status' not in cluster: continue if 'phase' not in cluster['status']: continue status = cluster['status']['phase'] name = cluster['metadata']['name'] namespace = cluster['metadata']['namespace'] if status == 'PendingDelete': pendingDeleteClusters.append( { 'name': name, "namespace": namespace } ) rawData = fetch_staging_clusters_json() clusters = json.loads(rawData) for cluster in clusters['items']: if 'status' not in cluster: continue if 'phase' not in cluster['status']: continue status = cluster['status']['phase'] name = cluster['metadata']['name'] namespace = cluster['metadata']['namespace'] if status == 'PendingDelete': pendingDeleteClusters.append( { 'name': name, "namespace": namespace } ) def post_to_feishu(): headers = { 'Content-Type': 'application/json' } if len(pendingDeleteClusters) == 0: return contents = [] for cluster in pendingDeleteClusters: contents.append( 'env: {}, id: {}'.format(cluster['namespace'], cluster['name']) ) payload_message = { "timestamp": str(int(time.time())), "msg_type": "interactive", "card": { "i18n_elements": { "en_us": [ { "tag": "div", "text": { "tag": "lark_md", "content": "**Pending Deletion Clusters**" }, "fields": [ { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, { "is_short": True, "text": { "tag": "lark_md", "content": "{}".format( '\n'.join(contents) ) } }, ] }, ] } } } response = requests.request( "POST", BOT_WEBHOOK, headers=headers, data=json.dumps(payload_message)) print(response.text) process_infra_clusters() post_to_feishu()