1
votes

I'm trying out terraform to set up an S3 + Cloudfront static site. Initially, I set up the site successfully, following the steps from https://alimac.io/static-websites-with-s3-and-hugo-part-1/

However, afterwards I changed the terraform state backend from local to s3 Now, when I perform terraform apply I get the following error:

Error: Error applying plan:

2 error(s) occurred:

* aws_cloudfront_distribution.primary_domain: 1 error(s) occurred:

* aws_cloudfront_distribution.primary_domain: CNAMEAlreadyExists: One or more of the CNAMEs you provided are already associated with a different resource.
    status code: 409, request id: <removed>
* aws_cloudfront_distribution.secondary_domain: 1 error(s) occurred:

* aws_cloudfront_distribution.secondary_domain: CNAMEAlreadyExists: One or more of the CNAMEs you provided are already associated with a different resource.
    status code: 409, request id: <removed>

Any ideas about why this might be happening and what can I do to fix this issue?

1

1 Answers

3
votes

Terraform uses the state file to keep track of resources it manages. If it does not have a particular resource (in this case probably your aws_cloudfront_distribution.primary_domain resource), it will create a new one and store the ID of that new resource in your state file.

It looks like you did a terraform apply with your local state file, changed the backend to s3 without porting the state to s3, then ran terraform apply again. This second S3-backed run has a blank state, so it tried to recreate your aws_cloudfront_distribution resources again. Looks like the error indicates a conflict in using the same CNAME for two distributions, which is what would happen if you ran Terraform twice without keeping track of state in between.

You have a couple of options to fix this:

  • Go back to using your existing local state file, terraform destroy to remove the resources it created, switch back to s3, then terraform apply to start anew. Be aware that this will actually delete resources.
  • Properly change your backend and reinitialize, then answer "yes" to copying your remote state to S3.
  • terraform import the resources you created with your local state file into your S3 backend. Do this with terraform import aws_cloudfront_distribution.primary_domain <EXISTING CLOUDFRONT DIST. ID>.