如何通过设置保留期删除带有标签的快照

How to delete the snapshots with a tag by setting the retention period

我有一个脚本可以在保留期后删除快照。它运行良好并删除了超过保留期的快照。但我必须用标签过滤它。意味着只应删除具有特定标签的快照。

from botocore.exceptions import ClientError
import datetime

# Set the global variables
globalVars  = {}
globalVars['Owner']                 = "Cloud"
globalVars['Environment']           = "Test"
globalVars['REGION_NAME']           = "ap-south-1"
globalVars['tagName']               = "Testing"
globalVars['findNeedle']            = "DeleteOn"
globalVars['RetentionDays']         = "1"
globalVars['tagsToExclude']         = "Do-Not-Delete"

ec2_client = boto3.client('ec2')

"""
This function looks at *all* snapshots that have a "DeleteOn" tag containing
the current day formatted as YYYY-MM-DD. This function should be run at least
daily.
"""

def janitor_for_snapshots():
    account_ids = list()
    account_ids.append( boto3.client('sts').get_caller_identity().get('Account') )

    snap_older_than_RetentionDays = ( datetime.date.today() - datetime.timedelta(days= int(globalVars['RetentionDays'])) ).strftime('%Y-%m-%d')
    delete_today = datetime.date.today().strftime('%Y-%m-%d')

    tag_key = 'tag:' + globalVars['findNeedle']
    filters = [{'Name': tag_key, 'Values': [delete_today]},]

    # filters={ 'tag:' + config['tag_name']: config['tag_value'] }

    # Get list of Snaps with Tag 'globalVars['findNeedle']'
    snaps_to_remove = ec2_client.describe_snapshots(OwnerIds=account_ids,Filters=filters)

    # Get the snaps that doesn't have the tag and are older than Retention days
    all_snaps = ec2_client.describe_snapshots(OwnerIds=account_ids)
    for snap in all_snaps['Snapshots']:
        if snap['StartTime'].strftime('%Y-%m-%d') <= snap_older_than_RetentionDays:
            snaps_to_remove['Snapshots'].append(snap)

    snapsDeleted = {'Snapshots': []}

    for snap in snaps_to_remove['Snapshots']:
        try:
            ec2_client.delete_snapshot(SnapshotId=snap['SnapshotId'])
            snapsDeleted['Snapshots'].append({'Description': snap['Description'], 'SnapshotId': snap['SnapshotId'], 'OwnerId': snap['OwnerId']})
        except ClientError as e:
            if "is currently in use by" in str(e):
                print("Snapshot {} is part of an AMI".format(snap.get('SnapshotId')))

    snapsDeleted['Status']='{} Snapshots were Deleted'.format( len(snaps_to_remove['Snapshots']))

    return snapsDeleted

def lambda_handler(event, context):
    return janitor_for_snapshots()

if __name__ == '__main__':
    lambda_handler(None, None)

我只想删除带有 "DeleteOn" 标签的快照。但是这个脚本会删除所有超过保留期的内容。它不检查标签部分。

请检查并帮助解决这个问题。 谢谢。

如果您询问如何修复代码,使其只删除快照:

  • 有给定的标签,AND
  • 已超过保留期

然后仔细查看您的代码。

这部分:

# Get list of Snaps with Tag 'globalVars['findNeedle']'
snaps_to_remove = ec2_client.describe_snapshots(OwnerIds=account_ids,Filters=filters)

正在按标签获取快照列表。太棒了!

然后这部分:

# Get the snaps that doesn't have the tag and are older than Retention days
all_snaps = ec2_client.describe_snapshots(OwnerIds=account_ids)
for snap in all_snaps['Snapshots']:
    if snap['StartTime'].strftime('%Y-%m-%d') <= snap_older_than_RetentionDays:
        snaps_to_remove['Snapshots'].append(snap)

正在获取新的快照列表并检查保留。

然后,生成的 snaps_to_remove 包含两者的结果。

您将需要结合您的逻辑,以便只添加满足两个条件的快照,而不是单独编译快照列表。