def lambda_handler()

in lambda/take_snapshots_rds/lambda_function.py [0:0]


def lambda_handler(event, context):

    client = boto3.client('rds', region_name=REGION)
    response = paginate_api_call(client, 'describe_db_instances', 'DBInstances')
    now = datetime.now()
    pending_backups = 0
    filtered_instances = filter_instances(TAGGEDINSTANCE, PATTERN, response)
    filtered_snapshots = get_own_snapshots_source(PATTERN, paginate_api_call(client, 'describe_db_snapshots', 'DBSnapshots'), BACKUP_INTERVAL)

    for db_instance in filtered_instances:

        timestamp_format = now.strftime(TIMESTAMP_FORMAT)

        if requires_backup(BACKUP_INTERVAL, db_instance, filtered_snapshots):

            backup_age = get_latest_snapshot_ts(
                db_instance['DBInstanceIdentifier'],
                filtered_snapshots)

            if backup_age is not None:
                logger.info('Backing up %s. Backed up %s minutes ago' % (
                    db_instance['DBInstanceIdentifier'], ((now - backup_age).total_seconds() / 60)))

            else:
                logger.info('Backing up %s. No previous backup found' %
                            db_instance['DBInstanceIdentifier'])

            snapshot_identifier = '%s-%s' % (
                db_instance['DBInstanceIdentifier'], timestamp_format)

            try:
                response = client.create_db_snapshot(
                    DBSnapshotIdentifier=snapshot_identifier,
                    DBInstanceIdentifier=db_instance['DBInstanceIdentifier'],
                    Tags=[{'Key': 'CreatedBy', 'Value': 'Snapshot Tool for RDS'}, {
                        'Key': 'CreatedOn', 'Value': timestamp_format}, {'Key': 'shareAndCopy', 'Value': 'YES'}]
                )
            except Exception as e:
                pending_backups += 1
                logger.info('Could not create snapshot %s (%s)' % (snapshot_identifier, e))
        else:

            backup_age = get_latest_snapshot_ts(
                db_instance['DBInstanceIdentifier'],
                filtered_snapshots)

            logger.info('Skipped %s. Does not require backup. Backed up %s minutes ago' % (
                db_instance['DBInstanceIdentifier'], (now - backup_age).total_seconds() / 60))

    if pending_backups > 0:
        log_message = 'Could not back up every instance. Backups pending: %s' % pending_backups
        logger.error(log_message)
        raise SnapshotToolException(log_message)