CloudFormation creation of CloudFront distribution with logging bucket

Viewed 2969

Trying to provision a static website bucket that's distributed by CloudFront.

The following CloudFormation template works if I omit the Logging configuration for the distribution:

{
...

"PrimeBucket": {
    "Properties": {
        "AccessControl": "PublicRead",
        "WebsiteConfiguration": {
            "ErrorDocument": "error.html",
            "IndexDocument": "index.html"
        }
    },
    "Type": "AWS::S3::Bucket"
},
"PrimeBucketDistribution": {
    "Properties": {
        "DistributionConfig": {
            "DefaultCacheBehavior": {
                "AllowedMethods": [
                    "GET",
                    "HEAD",
                    "OPTIONS"
                ],
                "ForwardedValues": {
                    "QueryString": "false"
                },
                "TargetOriginId": "BucketOrigin",
                "ViewerProtocolPolicy": "allow-all"
            },
            "Enabled": "true",
            "Logging": {
                "Bucket": {
                    "Ref": "PrimeBucketLogs"
                },
                "IncludeCookies": "false"
            },
            "Origins": [
                {
                    "DomainName": {
                        "Fn::GetAtt": [
                            "PrimeBucket",
                            "DomainName"
                        ]
                    },
                    "Id": "BucketOrigin",
                    "S3OriginConfig": {}
                }
            ]
        }
    },
    "Type": "AWS::CloudFront::Distribution"
},
"PrimeBucketLogs": {
    "Type": "AWS::S3::Bucket"
}
}

If I include Logging I get the error:

The parameter Logging Bucket does not refer to a valid S3 bucket.

Is there any extra magic that needs to be applied to the logging bucket in order for it to be compatible with CloudFront? Couldn't find anything in the docs.

2 Answers

Using Terraform, to avoid this error: Error: error updating CloudFront Distribution InvalidArgument: The parameter Logging Bucket does not refer to a valid S3 bucket.

You can workaround logging name if S3 bucket is created in the same code:

resource "aws_s3_bucket" "my_s3_sample" {
  bucket        = "simple-application"
  force_destroy = true
}

resource "aws_cloudfront_distribution" "my_cloudfront_sample" {
...
..
  logging_config {
    include_cookies = true
    bucket =  "${aws_s3_bucket.my_s3_sample.id}.s3.amazonaws.com"
    prefix          = "logs/cloudfront/my_cloudfront_sample/"
  }
}

Or importing S3 with Datasource

data "aws_s3_bucket" "selected" {
  bucket = "simple-application"
}

resource "aws_cloudfront_distribution" "my_cloudfront_sample" {
...
..
  logging_config {
    include_cookies = true
    bucket =  "${data.aws_s3_bucket.selected.id}.s3.amazonaws.com"
    prefix          = "logs/cloudfront/my_cloudfront_sample/"
  }
}
Related