python-3.x - 使用 Python、Lambda 删除旧的 EBS 卷快照,除了少数带有某些标签的快照
问题描述
我正在学习 Python 并设法完成了上述工作。但我的脚本似乎不是最优的。有人可以帮助进行审查并提出改进建议吗?
import boto3
from datetime import datetime,timedelta
REGION = "ap-southeast-1"
retention_days = 45
account_id = boto3.client('sts').get_caller_identity().get('Account')
ec2 = boto3.client('ec2', region_name=REGION)
def lambda_handler(event, context):
now = datetime.now()
outdated_snapID = []
retain_snapID = []
result = ec2.describe_snapshots(OwnerIds=[account_id])
for snapshot in result['Snapshots']:
# 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):
outdated_snapID.append(snapshot['SnapshotId'])
retain_snap = ec2.describe_snapshots(OwnerIds=[account_id], Filters=[{'Name': 'tag:Retain', 'Values': ['True', 'true']}])
for snap in retain_snap['Snapshots']:
# Remove timezone info from snapshot in order for comparison to work below
snapshot_time = snap['StartTime'].replace(tzinfo=None)
if (now - snapshot_time) > timedelta(retention_days):
retain_snapID.append(snap['SnapshotId'])
# Remove retained snapshotID's from the outdated array
for i in retain_snapID:
outdated_snapID.remove(i)
for x in outdated_snapID:
delete_snapshot(x)
def delete_snapshot(snapshotID):
try:
ec2.delete_snapshot(SnapshotId=snapshotID)
except Exception as ex:
print("Something went wrong:", ex)
pass
解决方案
推荐阅读
- python - 有没有办法通过 python 将任务删除到 Windows 任务调度程序?
- android - 适用于 Android-NDK 应用程序构建的 Windows 与 Linux
- flutter - 如何创建一个在所有屏幕上都保持活跃的小部件?像 Spotify 的迷你播放器
- django - 找不到页面
- dart - Dart 从 base64 转换为 HEX
- python - ValueError: int() 以 10 为底的无效文字:'slug-1-2'
- linux - 在 zsh Alias 中转义反斜杠和双引号
- excel - Excel - 根据表格中一行中的多个“x”条目返回多个列标题?
- javascript - 在 HTML 中上传后如何显示图像名称?
- java - jar:ModulePackages 类文件属性中缺少包 org.apache.catalina.ssi