import boto3 import json import time import requests from datetime import date, timedelta BOT_SECRET = "Rk7vQ3pmlG1uIrfQmWWvab" BOT_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/1132de87-edb3-4032-842a-49a1e23b88d3" def post_to_feishu(ebs): 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": "**EBS Robot**" }, "fields": [ { "is_short": False, "text": { "tag": "lark_md", "content": "" } }, { "is_short": True, "text": { "tag": "lark_md", "content": "自动清理: {} 块盘".format(len(ebs)) } } ] }, ] } } } response = requests.request( "POST", BOT_WEBHOOK, headers=headers, data=json.dumps(payload_message)) print(response.text) def clean_ebs(): cleaned_volumes = [] for region in ["us-west-2", "us-east-1", "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "eu-central-1"]: print("scan region {}".format(region)) client = boto3.client('ec2', region_name=region) volumes = client.describe_volumes() for volume in volumes["Volumes"]: status = volume['State'] if 'Tags' not in volume: continue tags = volume['Tags'] csiVolumeName = '' volumeName = '' pvcName = '' for tag in tags: if tag['Key'] == 'CSIVolumeName': csiVolumeName = tag['Value'] if tag['Key'] == 'Name': volumeName = tag['Value'] if tag['Key'] == "kubernetes.io/created-for/pvc/name": pvcName = tag['Value'] if 'prometheus' in pvcName or 'etcd' in pvcName: continue if status == "available": if 'pv-shoot' in csiVolumeName: print("delete volume {} in {}, tags {}".format( volume['VolumeId'] , region, tags)) client.delete_volume( VolumeId=volume['VolumeId'], DryRun=False ) cleaned_volumes.append(volume['VolumeId']) continue if 'shoot--' in volumeName: print("delete volume {} in {}, tags {}".format( volume['VolumeId'] , region, tags)) client.delete_volume( VolumeId=volume['VolumeId'], DryRun=False ) cleaned_volumes.append(volume['VolumeId']) return cleaned_volumes def lambda_handler(event, context): cleaned_volumes = clean_ebs() print("done") if len(cleaned_volumes) > 0: post_to_feishu(cleaned_volumes) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') }