【发布时间】:2011-07-15 21:13:30
【问题描述】:
(交叉发布到boto-users)
给定一个图像 ID,如何使用 boto 将其删除?
【问题讨论】:
标签: python amazon-ec2 boto
(交叉发布到boto-users)
给定一个图像 ID,如何使用 boto 将其删除?
【问题讨论】:
标签: python amazon-ec2 boto
您使用 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()
(编辑):实际上已经查看了 2.0 的在线文档,还有另一种方法。
确定了镜像ID后,就可以使用boto.ec2.connection的deregister_image(image_id)方法了……我猜的也是这样。
【讨论】:
使用较新的 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 快照
【讨论】:
对于 Boto2,请参阅 katriels answer。在这里,我假设您使用的是 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)
如果您拥有必要的权限,您应该会看到 Request would have succeeded, but DryRun flag is set 异常。要摆脱该示例,请忽略 DryRun 并使用:
ami.deregister() # WARNING: This will really delete the AMI
This blog post 详细阐述了如何使用 Boto3 删除 AMI 和快照。
【讨论】:
脚本将 AMI 及其关联的快照延迟。确保您拥有运行此脚本的正确权限。
输入 - 请传递区域和 AMI ids(n) 作为输入
import boto3
import sys
def main(region,images):
region = sys.argv[1]
images = sys.argv[2].split(',')
ec2 = boto3.client('ec2', region_name=region)
snapshots = ec2.describe_snapshots(MaxResults=1000,OwnerIds=['self'])['Snapshots']
# loop through list of image IDs
for image in images:
print("====================\nderegistering {image}\n====================".format(image=image))
amiResponse = ec2.deregister_image(DryRun=True,ImageId=image)
for snapshot in snapshots:
if snapshot['Description'].find(image) > 0:
snap = ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'],DryRun=True)
print("Deleting snapshot {snapshot} \n".format(snapshot=snapshot['SnapshotId']))
main(region,images)
【讨论】: