Skip to content

Instantly share code, notes, and snippets.

@ffturan
Created October 21, 2020 15:07
Show Gist options
  • Save ffturan/8503178618eb8adb4d825408fd13c17e to your computer and use it in GitHub Desktop.
Save ffturan/8503178618eb8adb4d825408fd13c17e to your computer and use it in GitHub Desktop.
Lists number of AWS snapshots associated and not associated with an AMI
#!/usr/bin/env python3
# ~~~~~~~~~~
# Lists number of snapshots associated and not associated with an AMI
# Requires : AWS PROFILE/REGION/ACCOUNT ID
#
# Usage: ./ec2_snapshot_usage.py <aws-profile> <aws-region> <aws-account-id>
# Usage: ./ec2_snapshot_usage.py myawsprofile us-east-1 111111111111
#
# Expected Output:
# Total number of Snapshots: <number>
# Number of Snapshots associated with AMIs: <number>
# Number of Snapshots not associated with AMIs: <number>
# ~~~~~~~~~~
import boto3
import sys
from botocore.exceptions import ClientError
def sortSecond(data):
return data[1]
def connect_aws(vProfile,vRegion):
try:
boto3.setup_default_session(profile_name=vProfile,region_name=vRegion)
worker = boto3.client('ec2')
return worker
except ClientError as e:
print(e)
def find_ami_snapshots(vWorker):
try:
ami_snapshots_list=[]
response = vWorker.describe_images(Owners=['self',])
for item in response["Images"]:
for subitem in item['BlockDeviceMappings']:
for key,value in subitem.items():
if key == 'Ebs':
ami_snapshots_list.append(subitem['Ebs'].get("SnapshotId"))
return ami_snapshots_list
except ClientError as e:
print(e)
def find_all_snapshots(vWorker,vAccountId):
try:
all_snapshots_list=[]
response = vWorker.describe_snapshots(OwnerIds=[vAccountId,],)
for item in response["Snapshots"]:
all_snapshots_list.append(item["SnapshotId"])
return all_snapshots_list
except ClientError as e:
print(e)
def check_args():
if len(sys.argv) < 4:
print(f'Usage: {sys.argv[0]} profile-name region-name account-id')
exit()
#
# MAIN STARTS HERE
#
if __name__ == '__main__':
# Check args
check_args()
# Get args
gProfile=sys.argv[1]
gRegion=sys.argv[2]
gAccountId=sys.argv[3]
worker_ec2=connect_aws(gProfile,gRegion)
#
vAllSnapshots=find_all_snapshots(worker_ec2,gAccountId)
print(f'Total number of Snapshots: {len(vAllSnapshots)}')
vUsedSnapshots=find_ami_snapshots(worker_ec2)
print(f'Number of Snapshots associated with AMIs: {len(vUsedSnapshots)}')
#
stray_snapshots=[]
for item in vAllSnapshots:
if not item in vUsedSnapshots:
stray_snapshots.append(item)
#for snap in stray_snapshots:
# print(f'{snap} is not used by any AMIs ...')
print(f'Number of Snapshots not associated with AMIs: {len(stray_snapshots)}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment