Compare commits

...

3 Commits

Author SHA1 Message Date
lavenderguitar 69b5be11c0 Add previous scripts rewritten in python 2 years ago
lavenderguitar a67d6faeed Add script to delete old AMIs 2 years ago
lavenderguitar 6993b1e731 Add script to delete orphaned snapshots 2 years ago
  1. 42
      delete_aws_amis.py
  2. 46
      delete_aws_amis.sh
  3. 56
      delete_orphaned_snapshots.py
  4. 50
      delete_orphaned_snapshots.sh

42
delete_aws_amis.py

@ -0,0 +1,42 @@
import boto3
from datetime import datetime
# Replace with your own values
region = 'us-east-1'
date_cutoff = '2022-01-01'
# Initialize the EC2 client
ec2 = boto3.client('ec2', region_name=region)
# Get a list of all the AMIs in the account
all_amis = ec2.describe_images(Owners=['self'])
# Loop through the list and print the names and IDs of any AMIs that were created before the cutoff date
amis_to_delete = []
for ami in all_amis['Images']:
created_date = datetime.strptime(ami['CreationDate'][:10], '%Y-%m-%d')
cutoff_date = datetime.strptime(date_cutoff, '%Y-%m-%d')
if created_date < cutoff_date:
print(f"AMI {ami['ImageId']} ({ami['Name']}) was created before the cutoff date.")
amis_to_delete.append(ami)
# Ask the user for verification before deleting the AMIs
if not amis_to_delete:
print("No AMIs to delete.")
else:
confirmation = input(f"\nAre you sure you want to delete {len(amis_to_delete)} AMIs? (y/n): ")
if confirmation.lower() == 'y':
delete_snapshots = input("Do you also want to delete the associated snapshots? (y/n): ")
# Loop through the list of AMIs to delete and delete the associated snapshots if specified
for ami in amis_to_delete:
print(f"Deleting AMI {ami['ImageId']} ({ami['Name']})")
snapshot_ids = [block_device['Ebs']['SnapshotId'] for block_device in ami['BlockDeviceMappings']]
ec2.deregister_image(ImageId=ami['ImageId'])
if delete_snapshots.lower() == 'y':
for snapshot_id in snapshot_ids:
print(f"Deleting snapshot {snapshot_id}")
ec2.delete_snapshot(SnapshotId=snapshot_id)
else:
print(f"Skipping deletion of {len(snapshot_ids)} associated snapshots.")
else:
print("Aborting deletion of AMIs.")

46
delete_aws_amis.sh

@ -0,0 +1,46 @@
#!/bin/bash
# Replace with your own values
region="us-east-1"
date_cutoff="2022-01-01"
# Get a list of all the AMIs in the account
all_amis=$(aws ec2 describe-images --region $region --owners self)
# Loop through the list and print the names and IDs of any AMIs that were created before the cutoff date
amis_to_delete=""
while read -r line; do
ami_id=$(echo $line | jq -r '.ImageId')
name=$(echo $line | jq -r '.Name')
creation_date=$(echo $line | jq -r '.CreationDate')
if [[ "$creation_date" < "$date_cutoff" ]]; then
echo "AMI $ami_id ($name) was created before the cutoff date."
amis_to_delete="$amis_to_delete $ami_id"
fi
done <<< "$all_amis"
# Ask the user for verification before deleting the AMIs
if [[ -z "$amis_to_delete" ]]; then
echo "No AMIs to delete."
else
read -p "Are you sure you want to delete $(echo $amis_to_delete | wc -w) AMIs? (y/n): " confirmation
if [[ "$confirmation" == "y" ]]; then
read -p "Do you also want to delete the associated snapshots? (y/n): " delete_snapshots
# Loop through the list of AMIs to delete and delete the associated snapshots if specified
for ami_id in $amis_to_delete; do
echo "Deleting AMI $ami_id"
snapshot_ids=$(aws ec2 describe-images --image-ids $ami_id --region $region | jq -r '.Images[0].BlockDeviceMappings[].Ebs.SnapshotId')
aws ec2 deregister-image --image-id $ami_id --region $region
if [[ "$delete_snapshots" == "y" ]]; then
for snapshot_id in $snapshot_ids; do
echo "Deleting snapshot $snapshot_id"
aws ec2 delete-snapshot --snapshot-id $snapshot_id --region $region
done
else
echo "Skipping deletion of $(echo $snapshot_ids | wc -w) associated snapshots."
fi
done
else
echo "Aborting deletion of AMIs."
fi
fi

56
delete_orphaned_snapshots.py

@ -0,0 +1,56 @@
import boto3
def list_orphaned_snapshots():
# Connect to AWS using Boto3
ec2 = boto3.resource('ec2')
# Get a list of all snapshots
snapshots = ec2.snapshots.all()
# Get a list of all volumes
volumes = ec2.volumes.all()
# Create a set to hold the volume IDs
volume_ids = set()
# Add all volume IDs to the set
for volume in volumes:
volume_ids.add(volume.id)
# Create a list to hold the orphaned snapshots
orphaned_snapshots = []
# Check each snapshot to see if its volume ID is in the set
for snapshot in snapshots:
if snapshot.volume_id not in volume_ids:
orphaned_snapshots.append(snapshot.id)
# Return the list of orphaned snapshots
return orphaned_snapshots
def delete_snapshots(snapshot_ids):
# Connect to AWS using Boto3
ec2 = boto3.resource('ec2')
# Confirm with user before deleting snapshots
confirmation = input(f"Are you sure you want to delete {len(snapshot_ids)} snapshots? (y/n): ")
if confirmation.lower() != "y":
print("Aborted snapshot deletion.")
return
# Delete each snapshot in the list
for snapshot_id in snapshot_ids:
snapshot = ec2.Snapshot(snapshot_id)
snapshot.delete()
print(f"Deleted snapshot {snapshot_id}")
# Call the function to list orphaned snapshots
orphaned_snapshots = list_orphaned_snapshots()
# Print the list of orphaned snapshots
print("Orphaned Snapshots:")
for snapshot_id in orphaned_snapshots:
print(snapshot_id)
# Call the function to delete the orphaned snapshots
delete_snapshots(orphaned_snapshots)

50
delete_orphaned_snapshots.sh

@ -0,0 +1,50 @@
#!/bin/bash
# List orphaned snapshots in AWS
# Set AWS profile and region
export AWS_PROFILE=my_profile
export AWS_DEFAULT_REGION=us-east-1
# Get a list of all snapshots
snapshots=$(aws ec2 describe-snapshots --owner-ids self --query 'Snapshots[*].[SnapshotId,VolumeId]' --output text)
# Get a list of all volumes
volumes=$(aws ec2 describe-volumes --query 'Volumes[*].VolumeId' --output text)
# Create an array to hold the volume IDs
volume_ids=()
# Add all volume IDs to the array
for volume in $volumes; do
volume_ids+=($volume)
done
# Create an array to hold the orphaned snapshots
orphaned_snapshots=()
# Check each snapshot to see if its volume ID is in the array
while read snapshot; do
snapshot_id=$(echo $snapshot | awk '{print $1}')
volume_id=$(echo $snapshot | awk '{print $2}')
if [[ ! " ${volume_ids[@]} " =~ " ${volume_id} " ]]; then
orphaned_snapshots+=($snapshot_id)
fi
done <<< "$snapshots"
# Print the list of orphaned snapshots
echo "Orphaned Snapshots:"
for snapshot_id in "${orphaned_snapshots[@]}"; do
echo $snapshot_id
done
# Delete the orphaned snapshots
read -p "Are you sure you want to delete ${#orphaned_snapshots[@]} snapshots? (y/n): " confirmation
if [[ $confirmation =~ ^[Yy]$ ]]; then
for snapshot_id in "${orphaned_snapshots[@]}"; do
aws ec2 delete-snapshot --snapshot-id $snapshot_id
echo "Deleted snapshot $snapshot_id"
done
else
echo "Aborted snapshot deletion."
fi
Loading…
Cancel
Save