Search code examples
amazon-web-servicesterraformamazon-cloudfrontterraform-provider-aws

Error creating CloudFront Distribution: NoSuchOrigin:


I am trying to deploy a Cloudfront distribution with Terraform and getting an error while specifying the origin_id

Cloudfront is pointing at a load balancer via a Route53 lookup.

resource "aws_cloudfront_distribution" "my-app" {
  origin {
    custom_origin_config {
      http_port              = 443
      https_port             = 443
      origin_protocol_policy = "https-only"
      origin_ssl_protocols   = ["TLSv1.2"]
    }

    domain_name = "${var.domain_name}"
    origin_id   = "Custom-${var.domain_name}"
  }

...

  default_cache_behavior {
    allowed_methods  = ["GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "DELETE"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "${local.origin_id}"

...

where var.domain_name is a route53 record and local.origin_id is a unique id.

When performing the terraform apply I get this error:

aws_cloudfront_distribution.my-app: error creating CloudFront Distribution: NoSuchOrigin: One or more of your origins or origin groups do not exist.

The documentation states: origin_id (Required) - A unique identifier for the origin. which it is.


Solution

  • The error relates to the cache behaviour. You need to make sure that the target_origin_id relates to an origin_id within a cache behaviour.

    Like so:

    resource "aws_cloudfront_distribution" "my-app" {
      origin {
        custom_origin_config {
          http_port              = 443
          https_port             = 443
          origin_protocol_policy = "https-only"
          origin_ssl_protocols   = ["TLSv1.2"]
        }
    
        domain_name = "${var.domain_name}"
        origin_id   = "Custom-${var.domain_name}"
      }
    
    ...
    
      default_cache_behavior {
        allowed_methods  = ["GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "DELETE"]
        cached_methods   = ["GET", "HEAD"]
        target_origin_id = "Custom-${var.domain_name}"
    
    ...