Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day-18( lambda_handler) #36

Open
dev-abdullaev opened this issue Nov 4, 2023 · 2 comments
Open

Day-18( lambda_handler) #36

dev-abdullaev opened this issue Nov 4, 2023 · 2 comments

Comments

@dev-abdullaev
Copy link

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')

# 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

@priyamathavan
Copy link

thanks for your help i am able to complete the handson

@dev-abdullaev
Copy link
Author

rushi26102000

you are welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants