How to delete an AMI using boto?

Question:

(cross posted to boto-users)

Given an image ID, how can I delete it using boto?

Asked By: ripper234

||

Answers:

You use the deregister() API.

There are a few ways of getting the image id (i.e. you can list all images and search their properties, etc)

Here is a code fragment which will delete one of your existing AMIs (assuming it’s in the EU region)

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()

(edit): and in fact having looked at the online documentation for 2.0, there is another way.

Having determined the image ID, you can use the deregister_image(image_id) method of boto.ec2.connection … which amounts to the same thing I guess.

Answered By: liamf

With newer boto (Tested with 2.38.0), you can run:

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

or

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

The first will delete the AMI, the second will also delete the attached EBS snapshot

Answered By: katriel

For Boto2, see katriels answer. Here, I am assuming you are using Boto3.

If you have the AMI (an object of class boto3.resources.factory.ec2.Image), you can call its deregister function. For example, to delete an AMI with a given ID, you can use:

import boto3

ec2 = boto3.resource('ec2')

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

ami.deregister(DryRun=True)

If you have the necessary permissions, you should see an Request would have succeeded, but DryRun flag is set exception. To get rid of the example, leave out DryRun and use:

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

This blog post elaborates on how to delete AMIs and snapshots with Boto3.

Answered By: Philipp Claßen

Script delates the AMI and associated Snapshots with it. Make sure you have right privileges to run this script.

Inputs – Please pass region and AMI ids(n) as inputs

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)
Answered By: Shubham Jain

using the EC2.Image resource you can simply call deregister():

Example:

for i in ec2res.images.filter(Owners=['self']):
    print("Name: {}t Id: {}tState: {}n".format(i.name, i.id, i.state))
    i.deregister()

See this for using different filters:
What are valid values documented for ec2.images.filter command?

See also: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Image.deregister

Answered By: Ray Hulha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.