Skip to content

Instantly share code, notes, and snippets.

@mcanaves
Created September 14, 2018 21:11
Show Gist options
  • Save mcanaves/b33626d59861705a74ae93fc0fd52791 to your computer and use it in GitHub Desktop.
Save mcanaves/b33626d59861705a74ae93fc0fd52791 to your computer and use it in GitHub Desktop.
Deregister old AMIs with boto3
"""
Deregister retired AMIs.
This script deregister all images marked as retired more than a X days
and removes the associated snapshot volumes.
To be able to identify the marked ones as retired and the time when it was
done the following tag system is used:
- stage [dev|production|retired]: used to track the life cycle of an image.
- state-changed [YYYYMMDDHHSS]: datetime mark to track when
stage changes were made.
Code inspired and adapted from the book AWS System Administration
by Mike Ryan and Federico Lucifredi (O’Reilly).
"""
from datetime import datetime
import boto3
DATETIME_FORMAT = "%Y%m%d%H%M" # TODO: select format from input params with default
DELETE_DELTA = 7 # days TODO: select delta from input params with default
ec2 = boto3.resource("ec2") # TODO: select region from input params with default
for image in ec2.images.filter(
Filters=[
{"Name": "tag:stage", "Values": ["retired"]},
{"Name": "tag-key", "Values": ["state-changed"]}
],
Owners=["self"]
):
state_changed = next((tag["Value"] for tag in image.tags if tag["Key"] == "state-changed"))
state_changed = datetime.strptime(state_changed, DATETIME_FORMAT)
if (datetime.now()-state_changed).days > DELETE_DELTA:
devices = image.block_device_mappings
print(f"Deregistering image {image.id}")
image.deregister()
for device in devices:
if "Ebs" in device:
snapshot = ec2.Snapshot(device["Ebs"]["SnapshotId"])
print(f"Deleting snapshot {snapshot.id} for image {image.id}")
snapshot.delete()
else:
print("No image to delete")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment