Skip to content

Instantly share code, notes, and snippets.

@wenqiglantz
Created October 31, 2022 01:23
Show Gist options
  • Save wenqiglantz/2dd638f9292a7668ea5480afbea8491d to your computer and use it in GitHub Desktop.
Save wenqiglantz/2dd638f9292a7668ea5480afbea8491d to your computer and use it in GitHub Desktop.
#######################################
# aws_s3_bucket_versioning, version update is needed to trigger cloudfront cache invalidation
#######################################
resource "aws_s3_bucket_versioning" "static_site_versioning" {
bucket = aws_s3_bucket.static_site.id
versioning_configuration {
status = "Enabled"
}
}
#######################################
# aws_s3_object, upload site to bucket
#######################################
resource "aws_s3_object" "static_site" {
# Must have bucket versioning enabled first
depends_on = [aws_s3_bucket_versioning.static_site_versioning]
bucket = aws_s3_bucket.static_site.id
key = "index.html"
acl = aws_s3_bucket_acl.static_site
source = "./build/index.html"
etag = filemd5("./build/index.html")
content_type = "text/html"
}
#######################################
# null_resource, invalidate CF cache when S3 website home page is updated, use path /* to invalidate whole site to save cost
#######################################
resource "null_resource" "invalidate_cf_cache" {
provisioner "local-exec" {
command = "aws cloudfront create-invalidation --distribution-id ${aws_cloudfront_distribution.static_site.id} --paths '/*'"
}
triggers = {
website_version_changed = aws_s3_object.static_site.version_id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment