如何解决Python Lambda:删除快照,但按标签排除
我对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:
…
我要删除的所有快照都比保留日期BUT早,但所有快照的标签均为“ retention”且值为“ keep”。
有人可以在这里帮我解决在for循环中如何做到这一点吗?
问题是:我是否还要在for循环中这样做并以某种方式过滤快照[标签] 或其他内容,还是在上面使用过滤器?
我想如果我在describe_snapshots中使用过滤器,我只会获得带有标记的快照。 但是我想检索所有快照,然后对所有带有标签的快照运行delete命令。
我们将不胜感激。预先感谢
解决方法
首先,我在not_delete_snaps
列表中列出所有需要保留的快照ID。然后计算retention_days
。您可以根据需要进行更改。
最后,循环所有快照,并检查not_delete_snaps
中是否存在snashot 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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。