python(boto3)程序按说明删除AWS中的旧快照

时间:2019-03-08 18:03:18

标签: python amazon-web-services aws-lambda

因此,我正在遵循此guide,它对于创建和删除3天以上的快照非常有帮助。问题是,作者发布的python脚本似乎删除了所有10天以上的快照。在我的环境中,由于某些原因,我有时会创建1级手动快照,因此我无法让此lambda函数删除那些快照,并且我希望它通过具有

的描述来过滤快照

"Created by Lambda backup function ebs-snapshots"

现在,作者发布了一种过滤创建的快照的方法,所以我试图通过过滤删除描述来模仿它,但是我只想让某人检查我的工作,和/或向我展示一种更好的方法,因为我拥有到目前为止是:

( Filters=[{'Description':['Created by Lambda backup function ebs-snapshots']}])

TLDR :如何在此代码中添加仅针对具有上述说明的快照的过滤器

这是要删除的作者代码:

# Delete snapshots older than retention period

import boto3
from botocore.exceptions import ClientError

from datetime import datetime,timedelta

def delete_snapshot(snapshot_id, reg):
    print "Deleting snapshot %s " % (snapshot_id)
    try:  
        ec2resource = boto3.resource('ec2', region_name=reg)
        snapshot = ec2resource.Snapshot(snapshot_id)
        snapshot.delete()
    except ClientError as e:
        print "Caught exception: %s" % e

    return

def lambda_handler(event, context):

    # Get current timestamp in UTC
    now = datetime.now()

    # AWS Account ID    
    account_id = '1234567890'

    # Define retention period in days
    retention_days = 10

    # Create EC2 client
    ec2 = boto3.client('ec2')

    # Get list of regions
    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regions:
        print "Checking region %s " % region['RegionName']
        reg=region['RegionName']

        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)

        # Filtering by snapshot timestamp comparison is not supported
        # So we grab all snapshot id's
        result = ec2.describe_snapshots( OwnerIds=[account_id] Filters=[{'Description':['Created by Lambda backup function ebs-snapshots']}])

        for snapshot in result['Snapshots']:
            print "Checking snapshot %s which was created on %s" % (snapshot['SnapshotId'],snapshot['StartTime'])

            # 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):
                print "Snapshot is older than configured retention of %d days" % (retention_days)
                delete_snapshot(snapshot['SnapshotId'], reg)
            else:
                print "Snapshot is newer than configured retention of %d days so we keep it" % (retention_days)

我更新的部分是: 结果= ec2.describe_snapshots(OwnerIds = [account_id]过滤器= [{'描述':['由Lambda备份函数ebs-snapshots']}]])

这在语法上正确吗?

0 个答案:

没有答案