import base64 import datetime import hmac import json import pytz import os import time import boto3 import requests feishu_webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/3d61f242-0da1-4ea0-95c4-57d73720aec5" instanceIDs = {} instanceCounts = 0 def post_bot_webhook(): post_infos = [] post_infos.append( { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, ) for region in instanceIDs.keys(): if len( instanceIDs[region] ) == 0: continue post_infos.append( { "is_short": True, "text": { "tag": "lark_md", "content": "Region={}:\n {}".format(region, ",\n".join( instanceIDs[region] )) } }, ) url = feishu_webhook payload_message = { "timestamp": str(int(time.time())), "msg_type": "interactive", "card": { "i18n_elements": { "en_us": [ { "tag": "div", "text": { "tag": "lark_md", "content": "** c5.9xlarge long live ** {}\n".format( datetime.datetime.today().strftime("%Y-%m-%d")), }, "fields": post_infos, }, ] } } } headers = { 'Content-Type': 'application/json' } response = requests.request( "POST", url, headers=headers, data=json.dumps(payload_message)) print(response.text) def dig_instances( region ): if region not in instanceIDs: instanceIDs[region] = [] ec2Client = boto3.client('ec2', region_name=region) response = ec2Client.describe_instances() for reservation in response['Reservations']: for instance in reservation['Instances']: instanceType = instance['InstanceType'] instanceId = instance['InstanceId'] launchTime = instance['LaunchTime'] instanceName = None component = None if 'Tags' not in instance: continue tags = instance['Tags'] for tag in tags: if tag['Key'] == 'Name': instanceName = tag['Value'] if tag['Key'] == 'component': component = tag['Value'] if instanceName is None: continue if datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) > launchTime + datetime.timedelta(hours=8): if instanceType == 'c5.9xlarge' and 'shoot' in instanceName and component not in ("tikv", "cdc"): instanceIDs[region].append( instanceId ) instanceCounts = instanceCounts + 1 def lambda_handler(event, context): for region in ["us-west-2", "us-east-1", "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "eu-central-1"]: dig_instances( region ) if instanceCounts > 0 : post_bot_webhook() return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } lambda_handler("", "")