0

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 Answers1

1

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

Aram
  • 5,537
  • 2
  • 30
  • 41
  • Thanks for your response but this recovery point will delete existing continuous backup and stops future continuous backup. how can we only delete only the snapshots without stopping the future backup – Madhu K Jul 11 '22 at 09:21
  • it will stop future continuous backups (PITR) not the regular backups. – Aram Jul 24 '22 at 21:20