( boto-usersにクロス投稿)
画像IDが与えられた場合、botoを使用してそれを削除するにはどうすればよいですか?
deregister()APIを使用します。
画像IDを取得する方法はいくつかあります(つまり、すべての画像を一覧表示してそのプロパティを検索するなど)
これは、既存のAMIの1つを削除するコードフラグメントです(EU地域にあると仮定します)
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)
1つ目はAMIを削除し、2つ目は添付されたEBSスナップショットも削除します
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)
必要な権限がある場合は、Request would have succeeded, but DryRun flag is set
例外が表示されます。例を取り除くには、省略しDryRun
て使用します。
ami.deregister() # WARNING: This will really delete the AMI
このブログ投稿では、Boto3を使用してAMIとスナップショットを削除する方法について詳しく説明しています。
スクリプトは、AMIとそれに関連するスナップショットを削除します。このスクリプトを実行するための適切な権限があることを確認してください。
入力-リージョンとAMIids(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)