如何使用boto删除AMI?

7 投票
5 回答
11535 浏览
提问于 2025-04-16 13:44

(同时发布到 boto-users)

给定一个图片的ID,我该如何使用boto来删除它呢?

5 个回答

6

如果你在使用Boto2,可以参考katriel的回答。在这里,我假设你正在使用Boto3。

如果你有一个AMI(这是一个boto3.resources.factory.ec2.Image类的对象),你可以调用它的deregister函数。比如说,如果你想删除一个特定ID的AMI,可以这样做:

import boto3

ec2 = boto3.resource('ec2')

ami_id = 'ami-1b932174'
ami = list(ec2.images.filter(ImageIds=[ami_id]).all())[0]

ami.deregister(DryRun=True)

如果你有足够的权限,你可能会看到一个提示:请求本来会成功,但设置了DryRun标志的异常。要解决这个问题,只需去掉DryRun,然后使用:

ami.deregister() # WARNING: This will really delete the AMI

这篇博客文章详细讲解了如何使用Boto3删除AMI和快照。

8

在更新版的boto(测试版本是2.38.0)中,你可以运行:

ec2_conn = boto.ec2.connect_to_region('xx-xxxx-x')
ec2_conn.deregister_image('ami-xxxxxxx')

或者

ec2_conn.deregister_image('ami-xxxxxxx', delete_snapshot=True)

第一个命令会删除AMI,第二个命令还会删除附加的EBS快照。

7

你可以使用deregister()这个接口。

获取图片ID有几种方法(比如你可以列出所有图片,然后查看它们的属性等等)。

下面是一个代码片段,它可以删除你现有的一个AMI(假设它在欧洲地区)。

connection = boto.ec2.connect_to_region('eu-west-1', \
                                    aws_access_key_id='yourkey', \
                                    aws_secret_access_key='yoursecret', \
                                    proxy=yourProxy, \
                                    proxy_port=yourProxyPort)


# This is a way of fetching the image object for an AMI, when you know the AMI id
# Since we specify a single image (using the AMI id) we get a list containing a single image
# You could add error checking and so forth ... but you get the idea
images = connection.get_all_images(image_ids=['ami-cf86xxxx'])
images[0].deregister()

(补充说明):其实我查看了2.0的在线文档,发现还有另一种方法。

确定了图片ID后,你可以使用boto.ec2.connection中的deregister_image(image_id)方法……我想这也是同样的意思。

撰写回答