Skip to content

Instantly share code, notes, and snippets.

@nirbhabbarat
Created February 9, 2018 06:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save nirbhabbarat/ee8772b7ba677fc45dc4ec4d26e4b19d to your computer and use it in GitHub Desktop.
Save nirbhabbarat/ee8772b7ba677fc45dc4ec4d26e4b19d to your computer and use it in GitHub Desktop.
Delete/Deregister 30 days old AMI in AWS using boto3 and python
#!/usr/bin/env python
##### USE ON YOUR OWN RISK - THIS IS GOING TO DEREGISTER AMI OLDER THAN 30 DAYS
import boto3
from dateutil.parser import parse
import datetime
age = 30
aws_profile_name = 'prod'
def days_old(date):
get_date_obj = parse(date)
date_obj = get_date_obj.replace(tzinfo=None)
diff = datetime.datetime.now() - date_obj
return diff.days
boto3.setup_default_session(profile_name = aws_profile_name)
ec2 = boto3.client('ec2')
amis = ec2.describe_images(Owners=[
'self'
])
for ami in amis['Images']:
create_date = ami['CreationDate']
ami_id = ami['ImageId']
# print ami['ImageId'], ami['CreationDate']
day_old = days_old(create_date)
if day_old > age:
print "deleting -> " + ami_id + " - create_date = " + create_date
# deregister the AMI
ec2.deregister_image(ImageId=ami_id)
@ramanjaneyareddyy
Copy link

Hi nirbhabbarat,

we are following to your scripts but we are getting on below error please help me on this issue.

InvalidDocumentContent: YAML not well-formed. at Line: 4, Column: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment