Deleting Snapshots managed by Backup using boto3

1.3k Views Asked by At

I wanted to delete the old snapshots from my aws account i used the following code but i am getting an error can you please suggest any code changes

this is the code

import json
import boto3
import datetime
client = boto3.client('ec2',region_name='us-east-1')
snapshots = client.describe_snapshots(OwnerIds=['self'])
def lambda_handler(event, context):
    print("printing snapshots")
    print(snapshots)
    Totalcount = 0
    deletecount = 0
    for snapshot in snapshots['Snapshots']:
        id = snapshot['SnapshotId']
        a = snapshot['StartTime']
        Totalcount = Totalcount + 1
        b = a.date()
        c = datetime.datetime.now().date()
        d = c-b
        try:
          if d.days>=31:
              id = snapshot['SnapshotId']
              deletecount = deletecount + 1
              client.delete_snapshot(SnapshotId=id)
              print ('Snapshot with Id = {id}  will be deleted '.format(id = id))
        except Exception as e:
          if 'InvalidSnapshot.InUse' in e.message:
              
              print("skipping this snapshot")
              continue
    print ('Total Snapshots in Account are {Totalcount}.'.format(Totalcount = Totalcount))
    print ('Deleted Snapshots of age grater than 31 are {deletecount}.'.format(deletecount = deletecount))

this the error

An error occurred (InvalidParameterValue) when calling the DeleteSnapshot operation: This snapshot is managed by the AWS Backup service and cannot be deleted via EC2 APIs. If you wish to delete this snapshot, please do so via the Backup console.
1

There are 1 best solutions below

2
On

Loos like your backups are done by AWS Backup. For that you can use AWS Backup client and use the delete-recovery-point API to do that:

https://docs.aws.amazon.com/cli/latest/reference/backup/delete-recovery-point.html