首页 > 解决方案 > 使用 Python、Lambda 删除旧的 EBS 卷快照,除了少数带有某些标签的快照

问题描述

我正在学习 Python 并设法完成了上述工作。但我的脚本似乎不是最优的。有人可以帮助进行审查并提出改进建议吗?

import boto3
from datetime import datetime,timedelta

REGION = "ap-southeast-1"
retention_days = 45
account_id = boto3.client('sts').get_caller_identity().get('Account')
ec2 = boto3.client('ec2', region_name=REGION)

def lambda_handler(event, context):
    now = datetime.now()
    outdated_snapID = []
    retain_snapID = []
    result = ec2.describe_snapshots(OwnerIds=[account_id])
    for snapshot in result['Snapshots']:
        # Remove timezone info from snapshot in order for comparison to work below
        snapshot_time = snapshot['StartTime'].replace(tzinfo=None)
        # Subtract snapshot time from now returns a timedelta 
        # Check if the timedelta is greater than retention days
        if (now - snapshot_time) > timedelta(retention_days):
            outdated_snapID.append(snapshot['SnapshotId'])
    retain_snap = ec2.describe_snapshots(OwnerIds=[account_id], Filters=[{'Name': 'tag:Retain', 'Values': ['True', 'true']}])
    for snap in retain_snap['Snapshots']:
        # Remove timezone info from snapshot in order for comparison to work below
        snapshot_time = snap['StartTime'].replace(tzinfo=None)
        if (now - snapshot_time) > timedelta(retention_days):
            retain_snapID.append(snap['SnapshotId'])
    # Remove retained snapshotID's from the outdated array
    for i in retain_snapID:
        outdated_snapID.remove(i)
    for x in outdated_snapID:
        delete_snapshot(x)

def delete_snapshot(snapshotID):
    try:
        ec2.delete_snapshot(SnapshotId=snapshotID)
    except Exception as ex:
        print("Something went wrong:", ex)
        pass

标签: python-3.xamazon-web-servicesaws-lambda

解决方案


推荐阅读