Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform can't create a CloudFront's origin with a static S3 website endpoint

I have a plan which uses two modules: bucket-website and cloudfront-website

Among other things (policies and such) inside the bucket module, there is the following resource for creating the bucket and serve it as a website:

resource "aws_s3_bucket" "bucket-website" {
  bucket = "${var.bucket_name}"
  region = "${var.region}"

  website {
    index_document = "index.html"
  }

  tags = "${local.common_tags}"
}

Also this module has the following output:

output "website_endpoint" {
  value = "${aws_s3_bucket.bucket-website.website_endpoint}"
}

The cloudfront-website module has a resource with all those cloudfront properties (IPs, cache stuff, etc), but the relevant part is:

resource "aws_cloudfront_distribution" "distribution" {
.....
  origin {
    domain_name = "${var.domain_name}"
    origin_id   = "${var.domain_name}"
  }
.....
}

The call to the cloudfront module in the plan passes the following parameter:

domain_name = "${module.bucket-website.website_endpoint}"

I can confirm that the value is correct, because in the log of terraform apply is can see:

  origin.123456.domain_name: "" => "foo.s3-website-eu-west-1.amazonaws.com"
  origin.123456.origin_id:   "" => "foo.s3-website-eu-west-1.amazonaws.com"

Which is the same endpoint I would use if I was doing this setup using just the AWS Console, i.e. get the bucket's static web endpoint (different to the standard bucket endpoint) and use it as the origin of Cloudfront.

However, for some reason Terraform is complaining about the domain name:

 * aws_cloudfront_distribution.distribution: error creating CloudFront Distribution: InvalidArgument: The parameter Origin DomainName does not refer to a valid S3 bucket.

And I'm already out of ideas. Everything looks good. The endpoint is correct. I have checked other examples and they also use ${aws_s3_bucket.<BUCKET_RESOURCE_NAME>.website_endpoint}, so I honestly don't understand what's wrong.

like image 894
Ay0 Avatar asked Jan 27 '23 15:01

Ay0


1 Answers

Just found the solution. When serving a S3 website through CloudFront, the following code must be added to the origin section, even though it's not specified elsewhere to do so.

    custom_origin_config {
      http_port              = "80"
      https_port             = "443"
      origin_protocol_policy = "http-only"
      origin_ssl_protocols   = ["TLSv1", "TLSv1.1", "TLSv1.2"]
    }
like image 131
Ay0 Avatar answered Feb 08 '23 16:02

Ay0