#!/usr/bin/env python3.7 import argparse import boto3 cli_parser = argparse.ArgumentParser(description="") cli_parser.add_argument('--region_name', type=str, default="eu-west-1") cli_parser.add_argument('--profile_name', type=str, default='default') cmdargs = cli_parser.parse_args() session = boto3.Session(profile_name=cmdargs.profile_name) ec2_client = session.client('ec2', region_name=cmdargs.region_name) icounter = 0 images_desc = ec2_client.describe_images(Owners=['self']) amis_to_snapshots = [dev['Ebs']['SnapshotId'] for image_desc in images_desc['Images'] for dev in image_desc['BlockDeviceMappings']] print(len(amis_to_snapshots)) snapshots = ec2_client.describe_snapshots(OwnerIds=['self',]) print(len(snapshots['Snapshots'])) orphaned_snapshots = [sh['SnapshotId'] for sh in snapshots['Snapshots'] if sh['SnapshotId'] not in amis_to_snapshots ] print('needs to be removed') print(len(orphaned_snapshots)) for i in orphaned_snapshots: response = ec2_client.delete_snapshot( SnapshotId=i ) print(response)