AWS Lambda to delete aws snapshots which are more than 2



import boto3
import datetime


def lambda_handler(event, context):
    client = boto3.client('rds')
    response = client.describe_db_instances()
    for dba in response['DBInstances']:
    snapshots = client.describe_db_snapshots(DBInstanceIdentifier=dba['DBInstanceIdentifier'], MaxRecords=50,SnapshotType='manual')['DBSnapshots']
    print(dba['DBInstanceIdentifier']+' '+str(len(snapshots)))
    snapshots.sort(key=getDate,reverse=True)
    if len(snapshots) > 2:
        num=0
        for eachsnap in snapshots:
            num=num+1
            if num>2:
                print('deleting '+ eachsnap['DBSnapshotIdentifier'])
                client.delete_db_snapshot(DBSnapshotIdentifier=eachsnap['DBSnapshotIdentifier'])
               
def getDate(ele):
    return ele['SnapshotCreateTime']

2 comments:

  1. Asking questions are truly nice thing if you are not understanding something totally, but this article presents pleasant understanding yet.

    ReplyDelete
  2. I have read so many articles or reviews on the topic of the blogger lovers but this article is in fact a pleasant article, keep it up.

    ReplyDelete