Created
July 4, 2022 22:17
-
-
Save valtoni/d2e2b396005a6df72cdfa2fad6fab17a to your computer and use it in GitHub Desktop.
AWS List of snapshots without AMI (Boto3)
This file contains 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
import boto3 | |
from boto3 import ec2 | |
import datetime | |
import re | |
from datetime import date | |
def is_attached(image, snapshot): | |
for mapping in image['BlockDeviceMappings']: | |
# Is it a machine ephemeral device? | |
if "VirtualName" in mapping: | |
if 'ephemeral' in mapping['VirtualName']: | |
return False | |
if mapping['Ebs']['SnapshotId'] == snapshot['SnapshotId']: | |
return True | |
return False | |
def info_orphan_snapshots(region_name, accountID, vdryRun=False): | |
filters = [ | |
{ | |
'Name': 'owner-id', | |
'Values': [ | |
accountID, | |
] | |
} | |
] | |
session = boto3.Session(region_name=region_name) | |
client = session.client("ec2", region_name) | |
snapshots = client.describe_snapshots(Filters=filters)["Snapshots"] | |
snapshots_ids = [ snapshot['SnapshotId'] for snapshot in snapshots ] | |
images = client.describe_images(Filters=filters)["Images"] | |
snapshots_attached = [ snapshot for snapshot in snapshots for image in images if is_attached(image, snapshot) ] | |
snapshots_attached_ids = [ item['SnapshotId'] for item in snapshots_attached ] | |
print("Snapthots count:", len(snapshots)) | |
print("Images count:", len(images)) | |
print("Images attached:", len(snapshots_attached)) | |
snapshots_dettached_ids = list(set(snapshots_ids) - set(snapshots_attached_ids)) | |
snapshots_dettached = [ snapshot for snapshot in snapshots for snapshot_dettached_id in snapshots_dettached_ids if snapshot_dettached_id == snapshot['SnapshotId'] ] | |
print("Images dettached: ", len(snapshots_dettached)) | |
for item in snapshots_dettached: | |
print(">", item['SnapshotId'], item['VolumeSize']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment