如何使用boto删除AMI?

rip*_*234 5 python amazon-ec2 boto

(交叉发布到boto用户)

给定图像ID,如何使用boto删除它?

小智 7

使用较新的boto(使用2.38.0测试),您可以运行:

ec2_conn = boto.ec2.connect_to_region('xx-xxxx-x')
ec2_conn.deregister_image('ami-xxxxxxx')
Run Code Online (Sandbox Code Playgroud)

要么

ec2_conn.deregister_image('ami-xxxxxxx', delete_snapshot=True)
Run Code Online (Sandbox Code Playgroud)

第一个将删除AMI,第二个也将删除附加的EBS快照

  • 怎么做同样的用户Boto3?问题是您无法使用Boto3中的deregister_image()函数删除快照.在Boto3中还有什么相反的方法?http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.deregister_image (6认同)

lia*_*amf 6

您使用deregister()API.

有几种获取图像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()
Run Code Online (Sandbox Code Playgroud)

(编辑):事实上,看过2.0的在线文档,还有另外一种方法.

确定了图像ID后,您可以使用boto.ec2.connection的deregister_image(image_id)方法...这与我猜的相同.


Phi*_*ßen 5

对于 Boto2,请参阅katriels 答案。在这里,我假设您使用的是 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)
Run Code Online (Sandbox Code Playgroud)

如果您拥有必要的权限,您应该会看到一个Request would have succeeded, but DryRun flag is set异常。要摆脱该示例,请省略DryRun并使用:

ami.deregister() # WARNING: This will really delete the AMI
Run Code Online (Sandbox Code Playgroud)

这篇博文详细说明了如何使用 Boto3 删除 AMI 和快照。