【问题标题】:Python Lambda: Delete Snapshots but Exclude by TagPython Lambda:删除快照但按标签排除
【发布时间】:2020-12-07 15:18:34
【问题描述】:

我对 python 和在 AWS 上编写 lambda 函数相当陌生。我现在阅读了很多博文和文章,最终偶然发现了我目前正在“测试”的以下脚本。

        … 
        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)
        
        # grab all snapshot id's
        result = ec2.describe_snapshots( OwnerIds=[account_id] )
        # result = ec2.describe_snapshots( Filters=[{'Name': 'tag:retention', 'Values': ['keep']},{'Name': 'owner-id','Values': ['111111111111']}] )
    
        for snapshot in result['Snapshots']:
            print "Checking snapshot %s which was created on %s" % (snapshot['SnapshotId'],snapshot['StartTime'])

            # for tag in snapshots:

            … 
        
        

我要删除所有比保留天数更早的快照,但所有具有标签“保留”且值为“保留”的快照除外。

谁能帮我看看如何在 for 循环中做到这一点?

问题是:我什至是否在 for 循环中执行此操作并以某种方式过滤 snapshot[Tags] 或其他什么,或者我是否使用上面的过滤器?

我想如果我在 describe_snapshots 中使用过滤器,我只会得到带有标签的快照。 但我想检索所有快照,然后对除带有标签的快照之外的所有快照运行删除命令。

我们将不胜感激。提前致谢

【问题讨论】:

  • 你能告诉我你的所有快照是否至少有一个标签吗?或者很少有标签,很少有没有标签。
  • 更新了代码,如果您遇到任何问题,请尝试告诉我。您只需根据需要更改retention_days = datetime.now() - timedelta(days=30) 保留天数。
  • 你测试了吗?

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


【解决方案1】:

首先,我在not_delete_snaps 列表中列出了所有需要保留的快照ID。然后计算retention_days。您可以根据需要进行更改。 最后,循环所有快照并检查not_delete_snaps 中是否存在快照ID。如果存在,则不要做任何事情,只需continue。然后检查快照 ID 是否早于retention_days。如果是,则删除所有旧快照。

import boto3
from datetime import datetime
from datetime import timedelta
from botocore.exceptions import ClientError


def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')

    snap_list = []
    marker = None
    paginator = ec2_client.get_paginator('describe_snapshots')
    while True:
        page_iterator = paginator.paginate(
            OwnerIds=['111111111111'],
            PaginationConfig={
                # 'MaxItems': 100,
                'PageSize': 100,
                'StartingToken': marker
            }
        )
        for page in page_iterator:
            snap_list += page['Snapshots']
        try:
            marker = page['Marker']
        except KeyError:
            break

    retention_days = datetime.now() - timedelta(days=7)
    for item in snap_list:
        start_time = item['StartTime']
        start_time_new = start_time.replace(tzinfo=None)
        keys = list(item.keys())
        try:
            if 'Tags' in keys and item['Tags'][0]['Key'] == 'retention' and item['Tags'][0]['Value'] == 'keep':
                continue
            if retention_days > start_time_new:
                ec2_client.delete_snapshot(
                    SnapshotId=item['SnapshotId'])
        except ClientError as e:
            if e.response['Error']['Code'] == 'InvalidSnapshot.InUse':
                print('Skipping snapshots which are in use')
            else:
                print("Unexpected error: %s" % e)

【讨论】:

  • 您可能希望在不使用过滤器的情况下拨打 2 次电话,而不是拨打 2 次电话,并跳过删除 retention 标记值为 keep 的那些电话。可能还会添加分页。
  • 好点。我可以添加分页。会做。但是,如果少数快照没有任何标签怎么办?然后根据标签检查将引发错误。如果所有快照都有标签,那么一次调用describe_snapshots 就足够了。
  • 您可以随时添加检查以查看是否存在密钥“保留”。或者只过滤键而不是值。
  • retention 无关。我可以添加检查是否有任何标签。如果快照没有任何标签,那么当我们描述它时,标签属性不会显示。它显示其他属性,如描述、所有者 ID 等,但不显示 Tags
  • 是的。一样。添加检查以查看 Tags 键是否存在。如果不跳过整个检查,或者可能让 OP 决定他/她想要做什么。
猜你喜欢
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多