Terraform无法使用静态S3网站端点创建CloudFront的原点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Terraform无法使用静态S3网站端点创建CloudFront的原点相关的知识,希望对你有一定的参考价值。

我有一个使用两个模块的计划:bucket-websitecloudfront-website

在存储桶模块内部(策略等)中,有以下资源用于创建存储桶并将其作为网站提供:

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

  website {
    index_document = "index.html"
  }

  tags = "${local.common_tags}"
}

此模块还具有以下输出:

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

cloudfront-website模块具有包含所有这些云端属性(IP,缓存内容等)的资源,但相关部分是:

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

计划中对cloudfront模块的调用传递以下参数:

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

我可以确认值是正确的,因为在terraform apply的日志中可以看到:

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

如果我仅使用AWS控制台进行此设置,即使获取存储桶的静态Web端点(与标准存储桶端点不同)并将其用作Cloudfront的来源,我将使用哪个端点。

但是,由于某种原因,Terraform抱怨域名:

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

我已经没有想法了。一切都很好看。端点是正确的。我检查过其他例子,他们也使用${aws_s3_bucket.<BUCKET_RESOURCE_NAME>.website_endpoint},所以老实说我不明白什么是错的。

答案

刚刚找到解决方案。通过CloudFront服务S3网站时,必须将以下代码添加到origin部分,即使在其他地方未指定这样做也是如此。

    custom_origin_config {
      http_port              = "80"
      https_port             = "443"
      origin_protocol_policy = "http-only"
      origin_ssl_protocols   = ["TLSv1", "TLSv1.1", "TLSv1.2"]
    }

以上是关于Terraform无法使用静态S3网站端点创建CloudFront的原点的主要内容,如果未能解决你的问题,请参考以下文章

动态/静态资源映射(Terraform)

即使存在 S3 存储桶,也无法对别名目标进行精细处理

无法使用“terraform init -reconfigure”将 S3 后端中的 Terraform 远程状态转换为本地状态

访问受限于 VPC 端点的 S3 网站从 VPC 内部获得 403

使用 S3 静态网站托管重定向到无法在 chrome 中工作的 WWW

用于谷歌存储的静态网站的 Terraform 谷歌存储桶 - 403