Reputation: 49
I want to delete the AMI image on the basis of its count. That is, I have defined the instance-ids in the name tag of the image, so that i can know of which instance the image is. I want to delete the images if the image count goes over 30 for that particular instance and the images deleted must be older ones not the newest ones.
Upvotes: 2
Views: 1478
Reputation: 4043
are you looking for something like this:
from boto.ec2 import connect_to_region
images = sorted(connect_to_region('us-west-1').get_all_images(owners='self'))
for candidates in images[30:]:
candidates.deregister()
assuming your .boto/boto.cfg is setup with your keys
update
If you want to do it by the date and not just order of AMIs (sorry I missed that) then you will need a custom script, something like:
from boto.ec2 import connect_to_region
images = (connect_to_region('us-west-1').get_all_images(owners='amazon'))
amis = {}
amis = dict([(image.id, image.creationDate) for image in images if 'ami' in image.id ])
candidates = [x for (x,y) in sorted(amis.items(), key=lambda (k,v): v)][:30]
import pdb; pdb.set_trace()
len(candidates)
for image in images:
print image.id
if str(image.id) in candidates:
print "try to remove"
image.deregister()
else:
print "current 30"
Upvotes: 1
Reputation: 8386
It looks quite custom.. so a custom script would be able to solve it. Using CLI commands like describe-images. You should also store the creation of the image as a tag.
I assume you don't have that much images ( thousands) so you can easily build an array about the different images, count them and select the latest one in O(n) time. Then you need to call the deregister-image command.
The script can run periodically.
The best would be to run it as a lambda function, but it is may not ready for it because of the lack of triggering. ( No cron style trigger at the moment.) But you may can trigger the function with the creation of a new AMI.
Upvotes: 0