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']

AWS Lambda to create a RDS Sanpshot






import boto3
import datetime

def lambda_handler(event, context):
    client = boto3.client('rds')
    response = client.describe_db_instances()
    for dba in response['DBInstances']:
      backup_name = 'backup-' + (dba['DBInstanceIdentifier'] + '-%s') % datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
      client.create_db_snapshot(
              DBInstanceIdentifier=dba['DBInstanceIdentifier'],
              DBSnapshotIdentifier= backup_name,
              Tags=[
                  {
                      'Key': 'BackupType',
                      'Value': 'long-term'
                  },
              ]
          )
      print(backup_name+ "Snapshot Created")