skip to Main Content

Before I used the resource aws_s3_object for syncing local files to S3 bucket. Back then updates in S3 triggered updating the connected distribution in CloudFront.

Now I replaced only the resource aws_s3_object mentioned above by null_resource / provisioner "local-exec" in the project. Then terraform apply only detected changes for the S3 bucket and no longer triggered updates for CloudFront.

What I did wrong / was missing here?

The related code:

Before (CloudFront is updated when S3 is updated):

resource "aws_s3_object" "site" {
  for_each     = fileset("./site/", "*")
  bucket       = xyz.id
  key          = each.value
  source       = "./site/${each.value}"
  etag         = filemd5("./site/${each.value}")
  content_type = "text/html;charset=UTF-8"
}

After (only S3 is updated, CloudFront is not updated):

resource "null_resource" "remove_and_upload_to_s3" {
  provisioner "local-exec" {
    command = "aws s3 sync ${path.module}/site s3://${aws_s3_bucket.xyz.id}"
  }
}

2

Answers


  1. In your CloudFront resource config, try to use depends_on:

    depends_on = [null_resource.remove_and_upload_to_s3]
    

    This will ensure that any changes to the null_resource will trigger an update to the CloudFront resource.

    Login or Signup to reply.
  2. I would probably go for the new resource terraform_data and then use the for_each with aws s3 cp instead of sync:

    resource "terraform_data" "remove_and_upload_to_s3" {
      for_each     = aws_s3_object.site
      triggers_replace = [
        each.value.etag
      ]
    
      provisioner "local-exec" {
        command = "aws s3 cp ${path.module}/site/${each.value.source} s3://${aws_s3_bucket.xyz.id}"
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search