def add_s3_bucket_lambda_event()

in templates/aws-cloudfront-waf/source/custom_resource/custom-resource.py [0:0]


def add_s3_bucket_lambda_event(log, bucket_name, lambda_function_arn, lambda_log_partition_function_arn, lambda_parser,
                               athena_parser):
    log.info("[add_s3_bucket_lambda_event] Start")
    
    try:
        s3_client = boto3.client('s3')
        if lambda_function_arn is not None and (lambda_parser or athena_parser):
            notification_conf = s3_client.get_bucket_notification_configuration(Bucket=bucket_name)

            log.info("[add_s3_bucket_lambda_event] notification_conf:\n %s"
                    % (notification_conf))

            new_conf = {}
            new_conf['LambdaFunctionConfigurations'] = []
    
            if 'TopicConfigurations' in notification_conf:
                new_conf['TopicConfigurations'] = notification_conf['TopicConfigurations']
    
            if 'QueueConfigurations' in notification_conf:
                new_conf['QueueConfigurations'] = notification_conf['QueueConfigurations']

            if lambda_parser:
                new_conf['LambdaFunctionConfigurations'].append({
                    'Id': 'Call Log Parser',
                    'LambdaFunctionArn': lambda_function_arn,
                    'Events': ['s3:ObjectCreated:*'],
                    'Filter': {'Key': {'FilterRules': [{'Name': 'suffix', 'Value': 'gz'}]}}
                })
    
            if athena_parser:
                new_conf['LambdaFunctionConfigurations'].append({
                    'Id': 'Call Athena Result Parser',
                    'LambdaFunctionArn': lambda_function_arn,
                    'Events': ['s3:ObjectCreated:*'],
                    'Filter': {'Key': {'FilterRules': [{'Name': 'prefix', 'Value': 'athena_results/'},
                                                       {'Name': 'suffix', 'Value': 'csv'}]}}
                })
    
            if lambda_log_partition_function_arn is not None:
                new_conf['LambdaFunctionConfigurations'].append({
                    'Id': 'Call s3 log partition function',
                    'LambdaFunctionArn': lambda_log_partition_function_arn,
                    'Events': ['s3:ObjectCreated:*'],
                    'Filter': {'Key': {
                        'FilterRules': [{'Name': 'prefix', 'Value': 'AWSLogs/'}, {'Name': 'suffix', 'Value': 'gz'}]}}
                })
    
            log.info("[add_s3_bucket_lambda_event] LambdaFunctionConfigurations:\n %s"
                     % (new_conf['LambdaFunctionConfigurations']))
    
            s3_client.put_bucket_notification_configuration(Bucket=bucket_name, NotificationConfiguration=new_conf)
    except Exception as error:
        log.error(error)
 
    log.info("[add_s3_bucket_lambda_event] End")