删除 AMI 映像

Deleting the AMI Image

我想根据计数删除 AMI 映像。也就是说,我在图像的名称标签中定义了 instance-ids,这样我就可以知道图像是哪个实例。如果该特定实例的图像计数超过 30,我想删除图像并且删除的图像必须是旧图像而不是最新图像。

它看起来很自定义..所以自定义脚本可以解决它。使用 CLI 命令,如 describe-images。 您还应该将图像的创建存储为标签。

我假设您没有那么多图像(数千张),因此您可以轻松地构建一个关于不同图像的数组,计算它们并 select O(n) 时间内的最新图像。然后需要调用deregister-image命令

脚本可以运行定期。

最好是 运行 它作为一个 lambda 函数,但由于缺少触发,它可能还没有准备好。 (目前没有 cron 样式触发器。)但是您可以通过创建新的 AMI 来触发该功能。

你在找这样的东西吗:

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"