def lambda_handler()

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


def lambda_handler(event, context):

    client = boto3.client('rds', region_name=REGION)
    response = paginate_api_call(client, 'describe_db_clusters', 'DBClusters')
    now = datetime.now()
    pending_backups = 0
    filtered_clusters = filter_clusters(PATTERN, response)
    filtered_snapshots = get_own_snapshots_source(PATTERN, paginate_api_call(client, 'describe_db_cluster_snapshots', 'DBClusterSnapshots'))

    for db_cluster in filtered_clusters:

        timestamp_format = now.strftime('%Y-%m-%d-%H-%M')

        if requires_backup(BACKUP_INTERVAL, db_cluster, filtered_snapshots):

            backup_age = get_latest_snapshot_ts(
                db_cluster['DBClusterIdentifier'],
                filtered_snapshots)

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

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

            if SNAPSHOT_NAME_PREFIX != 'NONE' and SNAPSHOT_NAME_PREFIX != '':
                snapshot_identifier = '%s-%s-%s' % (
                    SNAPSHOT_NAME_PREFIX, db_cluster['DBClusterIdentifier'], timestamp_format
                )
            else:
                snapshot_identifier = '%s-%s' % (
                    db_cluster['DBClusterIdentifier'], timestamp_format)

            try:
                response = client.create_db_cluster_snapshot(
                    DBClusterSnapshotIdentifier=snapshot_identifier,
                    DBClusterIdentifier=db_cluster['DBClusterIdentifier'],
                    Tags=[{'Key': 'CreatedBy', 'Value': 'Snapshot Tool for Aurora'}, {
                        'Key': 'CreatedOn', 'Value': timestamp_format}, {'Key': 'shareAndCopy', 'Value': 'YES'}]
                )
            except Exception as e:
                logger.error(e)
                pending_backups += 1
        else:

            backup_age = get_latest_snapshot_ts(
                db_cluster['DBClusterIdentifier'],
                filtered_snapshots)

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

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