You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hope, you are doing well. First of all, I am really happy for what you are doing for free. I have faced a small issue related to lambda_handler function that must delete if there is not running EC2 instance and volume attached to it while following day 18 Cost Optimization video but when I run the code you provided it did not delete the snapshot since snapshot has volume id showing it even if the instance and volume are deleted then decided to write another script similar to yours and it worked well. Tested several times so if you find this issue workable then accept it so that other followers would not be confused or get stuck.
# Get all EBS snapshots
snapshots = ec2.describe_snapshots(OwnerIds=['self'])['Snapshots']
# Get all active EC2 instance and volume IDs
instances = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])['Reservations']
active_instance_volume_ids = set()
# Get active instance and volume IDs
for reservation in instances:
for instance in reservation['Instances']:
for volume in instance['BlockDeviceMappings']:
active_instance_volume_ids.add(volume['Ebs']['VolumeId'])
# Iterate through snapshots and delete if not attached to any active instance or volume
deleted_snapshots_count = 0
for snapshot in snapshots:
snapshot_id = snapshot['SnapshotId']
volume_id = snapshot.get('VolumeId')
if not volume_id or volume_id not in active_instance_volume_ids:
# Delete the snapshot if it's not attached to any active instance or volume
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was not attached to any active instance or volume.")
deleted_snapshots_count += 1
return {
'statusCode': 200,
'body': f'Deleted {deleted_snapshots_count} unused EBS snapshots.'
}
`
Sincerely,
Zokhid
The text was updated successfully, but these errors were encountered:
Hello Abhishek.Veeramalla,
Hope, you are doing well. First of all, I am really happy for what you are doing for free. I have faced a small issue related to lambda_handler function that must delete if there is not running EC2 instance and volume attached to it while following day 18 Cost Optimization video but when I run the code you provided it did not delete the snapshot since snapshot has volume id showing it even if the instance and volume are deleted then decided to write another script similar to yours and it worked well. Tested several times so if you find this issue workable then accept it so that other followers would not be confused or get stuck.
`
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
`
Sincerely,
Zokhid
The text was updated successfully, but these errors were encountered: