import boto3 import json import requests import time webhook_url = 'https://open.feishu.cn/open-apis/bot/v2/hook/bde7fdc7-830b-45da-97eb-ee66975f05fc' def post_to_feishu(): headers = { 'Content-Type': 'application/json' } payload_message = { "timestamp": str(int(time.time())), "msg_type": "interactive", "card": { "i18n_elements": { "en_us": [ { "tag": "div", "text": { "tag": "lark_md", "content": "**AWS Seed Robot**" }, "fields": [ { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, { "is_short": True, "text": { "tag": "lark_md", "content": "自动关闭 AWS Us-east-1 Seed" } } ] }, ] } } } response = requests.request( "POST", webhook_url, headers=headers, data=json.dumps(payload_message)) print(response.text) def shut_down_seed(): asgClient = boto3.client('autoscaling', region_name="us-east-1") response = asgClient.describe_auto_scaling_groups() asgPrefix = ['staging-us-east-1-f01', "dev-rajeshwer-us-east-1", 'dev-us-east-1-zhangxc', 'staging-seed-us-east-1', 'dev-seed-us-east-1', 'dev-us-east-1-f'] print(response) asgs = response['AutoScalingGroups'] for asg in asgs: asgName = asg['AutoScalingGroupName'] match = False for asg in asgPrefix: if asg in asgName: match = True break if not match: continue print("process asg {}".format(asgName) ) asgClient.update_auto_scaling_group( AutoScalingGroupName=asgName, DesiredCapacity=0, MinSize=0, ) ec2Client = boto3.client('ec2', region_name="us-east-1") response = ec2Client.describe_instances() for reservation in response['Reservations']: for instance in reservation['Instances']: instanceName = None if 'Tags' not in instance: continue tags = instance['Tags'] for tag in tags: if tag['Key'] == 'Name': instanceName = tag['Value'] if instanceName is None: continue print("process ec2 {}".format(instanceName) ) if str(instanceName).startswith('shoot--') and 'master' in instanceName: response = ec2Client.terminate_instances( InstanceIds=[ instance['InstanceId'], ], ) def lambda_handler(event, context): shut_down_seed() post_to_feishu() return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') }