def check_app_log_bucket()

in templates/aws-cloudfront-waf/source/helper/helper.py [0:0]


def check_app_log_bucket(log, region, bucket_name):
    log.info("[check_app_log_bucket] Start")

    if bucket_name.strip() == "":
        raise Exception('Failed to configure access log bucket. Name cannot be empty!')

    # ------------------------------------------------------------------------------------------------------------------
    # Check if bucket exists (and inside the specified region)
    # ------------------------------------------------------------------------------------------------------------------
    exists = True
    s3_client = boto3.client('s3')
    try:
        response = s3_client.head_bucket(Bucket=bucket_name)
        log.info("[check_app_log_bucket]response: \n%s" % response)

    except botocore.exceptions.ClientError as e:
        # If a client error is thrown, then check that it was a 404 error.
        # If it was a 404 error, then the bucket does not exist.
        error_code = int(e.response['Error']['Code'])
        if error_code == 404:
            exists = False
        log.info("[check_app_log_bucket]error_code: %s." % error_code)
    # ------------------------------------------------------------------------------------------------------------------
    # Check if the bucket was created in the specified Region or create one (if not exists)
    # ------------------------------------------------------------------------------------------------------------------
    if exists:
        response = None
        try:
            response = s3_client.get_bucket_location(Bucket=bucket_name)
        except Exception as e:
            raise Exception(
                'Failed to access the existing bucket information. Check if you own this bucket and if it has proper access policy.')

        if response['LocationConstraint'] == None:
            response['LocationConstraint'] = 'us-east-1'
        elif response['LocationConstraint'] == 'EU':
            # Fix for github issue #72
            response['LocationConstraint'] = 'eu-west-1'

        if response['LocationConstraint'] != region:
            raise Exception(
                'Bucket located in a different region. S3 bucket and Log Parser Lambda (and therefore, you CloudFormation Stack) must be created in the same Region.')

    log.info("[check_app_log_bucket] End")