Created
August 6, 2020 10:14
-
-
Save hetul99/09f948d15b80e1ca9a4e4eba2b6b83d1 to your computer and use it in GitHub Desktop.
This will be followed by the CreateSnapShot lambda function. As CreateSnapShot will keep on making the backups( if you have it scheduled for everyday or every month) but won't delete it. This function will delete the snapshot and keep only the latest 3 copies of the snapshot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
import boto3 | |
def lambda_handler(event, context): | |
account_id = boto3.client('sts').get_caller_identity().get('Account') | |
ec2 = boto3.client('ec2') | |
regions = [region['RegionName'] | |
for region in ec2.describe_regions()['Regions']] | |
#Iterate over each Region | |
for region in regions: | |
print("Regions", region) | |
ec2 = boto3.client('ec2', region_name=region) | |
response = ec2.describe_snapshots(OwnerIds=[account_id]) | |
snapshots = response["Snapshots"] | |
# Sort snapshots by date ascending | |
snapshots.sort(key=lambda x: x["StartTime"]) | |
# Remove snapshots we want to keep (i.e. 3 most recent) | |
snapshots = snapshots[:-3] | |
for snapshot in snapshots: | |
id = snapshot['SnapshotId'] | |
try: | |
print("Deleting snapshot:", id) | |
ec2.delete_snapshot(SnapshotId=id) | |
except Exception as e: | |
if 'InvalidSnapshot. InUse' in e.message: | |
print("Snapshot {} in use, skipping.".format(id)) | |
continue | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment