Skip to content

Instantly share code, notes, and snippets.

@markobrien1
Created March 25, 2022 16:28
Show Gist options
  • Save markobrien1/56c573318dd1aaf0d2d3534f1eb12488 to your computer and use it in GitHub Desktop.
Save markobrien1/56c573318dd1aaf0d2d3534f1eb12488 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import boto3
import collections
import datetime
import dateutil.parser
import time
import sys
import json
import pytz
ec2_client = boto3.client('ec2', 'us-east-1')
utc = pytz.UTC
def get_amis():
print("getting amis")
images = ec2_client.describe_images(Owners=["self"])
return images
def get_volumes():
print("getting voulmes")
volumes = ec2_client.describe_volumes(Filters=[{'Name': 'status', 'Values': ['available']}])
return volumes
def get_snapshots():
print("getting snaphots")
snapshots = ec2_client.describe_snapshots(OwnerIds=["self"])
return snapshots
def delete_old_amis():
images = check_tag(get_amis(), "Images")
for item in images:
ami = item[0]
age = item[1]
ami_age = dateutil.parser.parse(ami["CreationDate"])
old_age = datetime.datetime.today() - datetime.timedelta(days=int(age))
if (ami_age.replace(tzinfo=None) < old_age) and (ImageName in ami["Name"]):
print(ami["ImageId"])
ec2_client.deregister_image(ImageId=ami["ImageId"])
def delete_old_volumes():
volumes = check_tag(get_volumes(), "Volumes")
for item in volumes:
volume = item[0]
age = item[1]
volume_age = volume["CreateTime"]
old_age = datetime.datetime.today() - datetime.timedelta(days=int(age))
if (volume_age.replace(tzinfo=None) < old_age):
print(volume["VolumeId"])
ec2_client.delete_volume(VolumeId=volume["VolumeId"])
def delete_old_snapshots():
snapshots = check_tag(get_snapshots(), "Snapshots")
for item in snapshots:
snapshot = item[0]
age = item[1]
snapshot_age = snapshot["StartTime"]
old_age = datetime.datetime.today() - datetime.timedelta(days=int(age))
if (snapshot_age.replace(tzinfo=None) < old_age):
print(snapshot["SnapshotId"])
ec2_client.delete_snapshot(SnapshotId=snapshot["SnapshotId"])
def check_tag(items, resource):
tagged_for_delete = []
for item in items[resource]:
if 'Tags' in item:
for tag in item['Tags']:
if tag['Key'] == 'Delete':
delete_tag = tag['Value']
tagged_for_delete.append(tuple([item,delete_tag]))
return tagged_for_delete
delete_old_volumes()
delete_old_amis()
delete_old_snapshots()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment