Skip to content

Instantly share code, notes, and snippets.

@keroloswilliam
Created March 26, 2020 09:42
Show Gist options
  • Save keroloswilliam/51282f9297565cfcf1837cfeb6e94b01 to your computer and use it in GitHub Desktop.
Save keroloswilliam/51282f9297565cfcf1837cfeb6e94b01 to your computer and use it in GitHub Desktop.

Revisions

  1. keroloswilliam created this gist Mar 26, 2020.
    37 changes: 37 additions & 0 deletions clean_orphaned_snapshots.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    #!/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)