Day-18 -------> add lambda function python boto3 code

Author: Makhan-solankiCreated Apr 2, 2026Updated Apr 9, 2026
import boto3
import json

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

    try:
          snapshots = ec2.describe_snapshots(OwnerIds=['self'])['Snapshots']
          instances = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])['Reservations']
          active_instance_volume_ids = set()

        for reservation in instances:
            for instance in reservation['Instances']:
                for volume in instance['BlockDeviceMappings']:
                    active_instance_volume_ids.add(volume['Ebs']['VolumeId'])

        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:
                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.'
        }
        
    except Exception as e:
        print(f"Error: {str(e)}")
        return {
            'statusCode': 500,
            'body': f'Error occurred: {str(e)}'
        }

If the ec2 instance is delete from the instance dashboard then the instance (EC2) and volume(EBS) is delete only and if you config snapshot for that instance then its not deleted so the lambda function code do these its check and delete this snapshots its usefull in its came to costoptimization

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