Deleting the snapshots if the associated snapshots-> volumes are not attached to any ec2 instance.

Venkateswara Reddy - Dec 9 '23 - - Dev Community

Pre requisite:
1.IAM Role
2.Lambda Function
3.Volume Snapshot-Ec2-Volume

Creation of IAM:

1.Here we have to create role for lambda function.
2.That role should have required permissions those are 1. describe Volume 2. Describe instances 3.Delete Volumes
3.So 1st dearch for IAM in the aws console and click on roles then select lamda then create the role
4.Then enter into that role and click on add permissions choose inline policy then select ec2 then search for volumes then select describe volumes and delete volumes and again search for instance then select describe instances then enter the policy name then create the policy.
5.Under role only now click on add permissions and now choose the attach policy then add our policy here what ever we created just now.

Creation of EC2-Volume-Snapshot:

1.Search for ec2 and create on EC2 instance when ever we create ec2 instance automatically volume will create with default settings no need to create volume explicitly.
2.We can create volume only irrespective of ec2 instance.
3.We can create snapshot by click on the left side snapshot option then select the volume and create the snapshot.

Creation of Lambda:

1.Search for lambda in the console for lambda and then click on the function then create the function by selecting the role what ever we created IAM role.
2.Then we have to write the code under the code section.


import boto3

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']}])
    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 not attached to any volume or the volume is not attached to a running instance
    for snapshot in response['Snapshots']:
        snapshot_id = snapshot['SnapshotId']
        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 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.")

Enter fullscreen mode Exit fullscreen mode

3.Then try to click on the test option and run the lambda function by manually our code will run successfully.
4.But our snapshot will not delete.
5.Why because the respective snapshot is associated to the volume is still attached to the ec2 instance.
6.If once we delete the ec2 instance our volume also will delete automatically. So now the associated snapshot volume is not there and also even if the volume is there if that volume is not associated to any instance also the snapshot will delete when ever we run the lambda function.
7.So we can automate this lambda function to run daily or weekly by using cloudwatch rules.
8.Here we can adjust the script like if snapshot is used 30 befor we want to delete the snapshot by using the lambda function by writing the code in such a way.
9.

. . . . . . . . . . . . .