Search code examples
amazon-web-servicesterraformamazon-cloudfront

How can I reference an exported certificate ARN in Terraform and avoid the 'undeclared resource' error?


I’m new to Terraform and can’t figure out why this doesn’t work. I’m trying to reference the certificate ARN (which is exported per Terraform docs), but I keep getting an error that it is undeclared. Anyone know why?

│ Error: Reference to undeclared resource
│
│   on cloudfront.tf line 17, in resource "aws_cloudfront_distribution" "cf_mysite_distribution":
│   17:     acm_certificate_arn = acm_mysite_certificate.arn
│
│ A managed resource "acm_mysite_certificate" "arn" has not been declared in the root module.

cf.tf:

resource "aws_cloudfront_distribution" "cf_mysite_distribution" {
  comment             = "mysite.com CloudFront Distribution"
  enabled             = true
  default_root_object = "index.html"

  viewer_certificate {
    acm_certificate_arn = acm_mysite_certificate.arn
    ssl_support_method  = "sni-only"
  }
  ...
}

acm.tf

resource "aws_acm_certificate" "acm_mysite_certificate" {
  domain_name       = "mysite.com"
  validation_method = "DNS"
}

resource "aws_acm_certificate_validation" "acm_mysite_certificate_validation" {
  certificate_arn         = aws_acm_certificate.aws_mysite_certificate.arn
  validation_record_fqdns = ["mysite.com", "www.mysite.com"]
}

I also tried depends_on, but that did not work either. Thank you in advance!

I tried using depends_on but that didn't work. I expected the cf.tf file to "wait" for the ACM ARN to exist...


Solution

  • As mentioned in the comments already the reference in the resource aws_cloudfront_distribution is incorrect.

    resource "aws_cloudfront_distribution" "cf_mysite_distribution" {
      comment             = "mysite.com CloudFront Distribution"
      enabled             = true
      default_root_object = "index.html"
    
      viewer_certificate {
        acm_certificate_arn = aws_acm_certificate.acm_mysite_certificate.arn ##CHANGE##
        ssl_support_method  = "sni-only"
      }
      ...
    }
    

    <RESOURCE TYPE>.<NAME>.<RESOURCE-ATTRIBUTE> is the format for referencing the attributes for Terraform managed resources.[1].

    [1]