Skip to content

Instantly share code, notes, and snippets.

@st-cyrill
Last active March 24, 2018 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st-cyrill/10c3c38b6b2e043812570a7f174422d0 to your computer and use it in GitHub Desktop.
Save st-cyrill/10c3c38b6b2e043812570a7f174422d0 to your computer and use it in GitHub Desktop.
AWS AMI AutoCleanImages
import boto3
import logging
from operator import itemgetter, attrgetter
images_limit = 1
code_pipeline = boto3.client('codepipeline')
def lambda_handler(event, context):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
session = boto3.Session()
ec2_client = session.client('ec2')
images = ec2_client.describe_images(Owners=["self"], Filters=[{"Name": "tag:autoclean", "Values": ["true"]}])
delta_image_num = len(images["Images"]) - images_limit
if delta_image_num > 0:
for i in range(delta_image_num):
image = sorted(images["Images"], key = itemgetter("CreationDate"))[i]
ec2_client.deregister_image(ImageId=image["ImageId"])
logger.info("Deregister Image:" + image["ImageId"])
ec2_client.delete_snapshot(SnapshotId=image["BlockDeviceMappings"][0]["Ebs"]["SnapshotId"])
logger.info("Delete SnapShot:" + image["BlockDeviceMappings"][0]["Ebs"]["SnapshotId"])
else:
logger.info("len(images) " + str(len(images["Images"])) + " < " + str(images_limit) + ".")
code_pipeline.put_job_success_result(jobId=event['CodePipeline.job']['id'])
return "Complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment