Skip to content

Commit

Permalink
Update ebs_stale_snapshosts.py
Browse files Browse the repository at this point in the history
  • Loading branch information
iam-veeramalla authored Jul 25, 2023
1 parent d3516b7 commit 92454be
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions day-18/ebs_stale_snapshosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,36 @@

def lambda_handler(event, context):
ec2 = boto3.client('ec2')

# Get all EBS snapshots
response = ec2.describe_snapshots(OwnerIds=['self'])

# Get all active EC2 instance IDs
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}])
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
active_instance_ids = set()

for reservation in instances_response['Reservations']:
for instance in reservation['Instances']:
active_instance_ids.add(instance['InstanceId'])
# Iterate through each snapshot and delete if it's stale

# Iterate through each snapshot and delete if it's not attached to any volume or the volume is not attached to a running instance
for snapshot in response['Snapshots']:
snapshot_id = snapshot['SnapshotId']
if 'VolumeId' in snapshot and snapshot['VolumeId'] not in active_instance_ids:
volume_id = snapshot.get('VolumeId')

if not volume_id:
# Delete the snapshot if it's not attached to any volume
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted stale EBS snapshot {snapshot_id}.")
print(f"Deleted EBS snapshot {snapshot_id} as it was not attached to any volume.")
else:
# Check if the volume still exists
try:
volume_response = ec2.describe_volumes(VolumeIds=[volume_id])
if not volume_response['Volumes'][0]['Attachments']:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was taken from a volume not attached to any running instance.")
except ec2.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidVolume.NotFound':
# The volume associated with the snapshot is not found (it might have been deleted)
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as its associated volume was not found.")

0 comments on commit 92454be

Please sign in to comment.