iam-veeramalla / aws-devops-zero-to-hero

AWS zero to hero repo for devops engineers to learn AWS in 30 Days. This repo includes projects, presentations, interview questions and real time examples.
https://www.youtube.com/@AbhishekVeeramalla
Apache License 2.0
6.64k stars 8.61k forks source link

Day-18( lambda_handler) #36

Open dev-abdullaev opened 11 months ago

dev-abdullaev commented 11 months ago

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 commented 6 months ago

thanks for your help i am able to complete the handson

dev-abdullaev commented 6 months ago

rushi26102000

you are welcome!