我想根据 AMI 映像的计数删除它。也就是说,我已经在图像的名称标签中定义了实例 ID,以便我可以知道图像是哪个实例。如果该特定实例的图像计数超过 30,并且删除的图像必须是较旧的图像而不是最新的图像,我想删除图像。
您是否正在寻找这样的东西:
from boto.ec2 import connect_to_region
images = sorted(connect_to_region('us-west-1').get_all_images(owners='self'))
for candidates in images[30:]:
candidates.deregister()
假设您的 .boto/boto.cfg 是用您的密钥设置的
更新
如果您想按日期而不是 AMI 的顺序执行此操作(对不起,我错过了),那么您需要一个自定义脚本,如下所示:
from boto.ec2 import connect_to_region
images = (connect_to_region('us-west-1').get_all_images(owners='amazon'))
amis = {}
amis = dict([(image.id, image.creationDate) for image in images if 'ami' in image.id ])
candidates = [x for (x,y) in sorted(amis.items(), key=lambda (k,v): v)][:30]
import pdb; pdb.set_trace()
len(candidates)
for image in images:
print image.id
if str(image.id) in candidates:
print "try to remove"
image.deregister()
else:
print "current 30"
它看起来很自定义..所以自定义脚本将能够解决它。使用 CLI 命令,如描述图像。还应将映像的创建存储为标记。
我假设您没有那么多图像(数千张),因此您可以轻松地构建一个关于不同图像的数组,对它们进行计数并在 O(n) 时间内选择最新的图像。然后,您需要调用取消注册映像命令。
脚本可以定期运行。
最好是将其作为 lambda 函数运行,但由于缺乏触发,它可能还没有准备好。(目前没有 cron 样式触发器。但是,您可以通过创建新的 AMI 来触发该功能。