簡體   English   中英

使用 Terraform 使上傳到 s3 的本地文件的雲端緩存無效

[英]Invalidate cloudfront cache of local files uploaded to s3 using Terraform

我原本打算發布這個問題的答案,但它似乎離題了,因為我有一個關於使上傳到 s3 的本地文件無效的特定用例。

我希望上傳到 s3 存儲桶並通過雲端服務的本地文件在更改時失效。

我的解決方案並不完美; 我已經詳細說明了一些注意事項。 然而,它確實滿足了我想要實現的目標。

resource null_resource cache_invalidation {
  # prevent invalidating cache before new s3 file is uploaded
  depends_on = [
    aws_s3_object.html_files,
    aws_s3_object.css_files,
  ]

  for_each = fileset("${path.module}/<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>/", "**")

  triggers = {
    hash = filemd5("<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>/${each.value}")
  }

  provisioner local-exec {
    # sleep is necessary to prevent throttling when invalidating many files; a dynamic sleep time would be more reliable
    # possible way of dealing with parallelism (though would lose the indiviual triggers): https://discuss.hashicorp.com/t/specify-parallelism-for-null-resource/20884/2
    command = "sleep 1; aws cloudfront create-invalidation --distribution-id ${aws_cloudfront_distribution.this.id} --paths '/${each.value}'"
  }
}

注意事項 1:第一次運行時,它會希望使所有列出的文件失效。

警告 2:如果要使數十個或更多文件失效,您可能會收到來自 AWS 的節流錯誤。 這只需要幾次初始運行apply


如果像我一樣你在<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>下有某些你不想失效的文件(對我來說我不需要這個用於img/子文件夾)你可以使用setintersection來過濾掉這些文件同時保持正確的路徑以供在triggers

resource null_resource cache_invalidation {
  # prevent invalidating cache before new s3 file is uploaded
  depends_on = [
    aws_s3_object.html_files,
    aws_s3_object.css_files,
  ]

  for_each = setsubtract(
    fileset("${path.module}/<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>/", "**"),
    [for file in fileset("${path.module}/<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>/img/", "*") : "img/${file}"],
  )

  triggers = {
    hash = filemd5("<LOCAL_FILES_TO_S3_TO_CLOUDFRONT>/${each.value}")
  }

  provisioner local-exec {
    # sleep is necessary to prevent throttling when invalidating many files
    # possible way of dealing with parallelism (though would lose the indiviual triggers): https://discuss.hashicorp.com/t/specify-parallelism-for-null-resource/20884/2
    command = "sleep 1; aws cloudfront create-invalidation --distribution-id ${aws_cloudfront_distribution.this.id} --paths '/${each.value}'"
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM