【问题标题】:Looking for a Python script to delete AWS snapshot by giving snapshot ID or Instance name as parameter with retention date通过将快照 ID 或实例名称作为保留日期的参数来寻找删除 AWS 快照的 Python 脚本
【发布时间】:2020-04-14 06:36:48
【问题描述】:

您好,我正在寻找 python 脚本,通过将快照 ID 或实例名称和保留期作为参数来删除快照。我有下面的脚本,它删除所有比保留期设置更早的快照,但是只想对特定实例名称执行删除。

# Delete snapshots older than retention period

import boto3
from botocore.exceptions import ClientError

from datetime import datetime,timedelta

def delete_snapshot(snapshot_id, reg):
    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):
    account_id = 'xxxxxxxxxxxxxxx'
    retention_days = 10
    # Get current timestamp in UTC
    now = datetime.now()

    # AWS Account ID

    # Define retention period in days

    # 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] )

        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)

【问题讨论】:

  • 您可以使用:Automating the Amazon EBS Snapshot Lifecycle - Amazon Elastic Compute Cloud,而不是编写自己的代码
  • 脚本需要describe_snapshots() 调用,然后使用delete_snapshot() 从该列表中删除所需的快照。请编辑您的问题,向我们展示您迄今为止编写的代码以及您面临的困难。
  • 谢谢。是的,我会更新我到目前为止的代码。我有一个代码可以删除所有早于我在代码中设置的保留期的快照。但是,我有一个不同的用例,我只想删除特定实例的快照。注意我有每个实例的实例名称或标签
  • @JohnRotenstein 我已经更新了我的问题中的代码。提前致谢

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


【解决方案1】:

您似乎在询问如何识别与给定快照关联的 Amazon EC2 实例。

一个简单的方法是在创建快照时添加一个标签,该标签包含实例 ID,甚至可能包含来自实例的标签。这意味着所有相关信息都将附加到快照本身。

否则,您可以:

  • describe_snapshots()的结果中获取VolumeId
  • 调用describe_volumes() 传入VolumeId
  • 如果卷仍附加到 EC2 实例,则 Attachments.InstanceId 将提供实例标识符

如果卷附加到实例,则此信息将不可用。但是,在启动实例时,标签可以从实例传播到卷。这可能是识别卷目的的好方法。

您也可以采取不同的方法:

  • 从实例 ID 列表开始
  • 对于每个实例:
    • 调用describe_instance()获取附加卷的VolumeId
    • 致电describe_snapshots(),传递VolumeId

这将只提供给定实例的快照,而不是从快照开始并必须发现实例。

您可以通过为给定标签调用describe_instances() 来对标签执行相同的操作,然后循环遍历每个结果实例。

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多