使用 terraform 创建 cloudfront 分发时出错。无效的查看者证书

AM *_*DEV 6 amazon-s3 amazon-web-services amazon-cloudfront amazon-route53 terraform-provider-aws

我正在尝试使用 Terraform 将 ReactJS 项目静态部署到 s3

我的 s3 存储桶 terraform 配置使用策略创建存储桶:

resource "aws_s3_bucket" "site" {
  bucket = var.domain
  acl = "public-read"

  policy = <<EOF
{
  "Version":"2012-10-17",
  "Statement":[{
        "Sid":"PublicReadForGetBucketObjects",
        "Effect":"Allow",
          "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::${var.domain}/*"]
    }
  ]
}
  EOF

  website {
      index_document = "index.html"
      error_document = "404.html"
  }
}
Run Code Online (Sandbox Code Playgroud)

带有必要 dns 的 route53 配置:

resource "aws_route53_zone" "main" {
  name = var.domain
}

resource "aws_route53_record" "root_domain" {
  zone_id = aws_route53_zone.main.zone_id
  name = var.domain
  type = "A"

  alias {
    name = aws_cloudfront_distribution.cdn.domain_name
    zone_id = aws_cloudfront_distribution.cdn.hosted_zone_id
    evaluate_target_health = false
  }
}
Run Code Online (Sandbox Code Playgroud)

云端配置:

resource "aws_cloudfront_distribution" "cdn" {
  origin {
    origin_id   = var.domain
    domain_name = aws_s3_bucket.site.bucket_regional_domain_name

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

  aliases = [var.domain]

  enabled             = true
  wait_for_deployment = false
  default_root_object = "index.html"

  custom_error_response {
      error_caching_min_ttl = 0
      error_code = 404
      response_code = 200
      response_page_path = "/index.html"
  }

  default_cache_behavior {
    allowed_methods  = ["GET", "HEAD", "OPTIONS"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = var.domain

    forwarded_values {
      query_string = true
      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "allow-all"
    min_ttl                = 0
    default_ttl            = 3600
    max_ttl                = 86400
  }

  price_class = "PriceClass_100"

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    cloudfront_default_certificate = true
  }
}
Run Code Online (Sandbox Code Playgroud)

即使我尝试使用 cloudfront 默认证书,我在运行后仍然收到以下错误terraform apply

Error: error creating CloudFront Distribution: InvalidViewerCertificate: To add an alternate domain name (CNAME) to a CloudFront distribution, you must attach a trusted certificate that validates your authorization to use the domain name.

AM *_*DEV 6

最后修复它,如果您想使用默认证书,您无法将备用域名添加到 CloudFront 分配,您将需要使用 Amazon 证书管理器生成 SSL 证书。换句话说,要完成这项工作,您需要aliases = [var.domain]在 CloudFront 配置部分中注释掉