How to delete an AMI using boto?

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.


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


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.