Automate your Website w/ Hugo, S3, & CloudFront

This is the script I use with my AWS CLI to “publish” my Hugo site to my static website S3 bucket. Once the files have been uploaded you will need to “invalidate” your Cloudfront cache in order for it to serve the latest content.

#!/bin/bash
set -e

## Update these with your code.
DISTRIBUTION_ID=E26LKJ862YPY4E
BUCKET_NAME=ownthe.cloud
PROFILE=myuser # Keep as "default" unless you use Profiles.

## Build hugo site in hugo working directory.
hugo -v

## Copy over pages - not static js/img/css/downloads
## Add --exclude 'img' --exclude 'js' --exclude 'downloads' --exclude 'css', to the top command to control cache behaivor.
aws s3 sync --profile ${PROFILE} --acl "public-read" --sse "AES256" public/ s3://${BUCKET_NAME}/

## Ensure static files are set to cache forever - cache for a month --cache-control "max-age=2592000"
# aws s3 sync --profile ${PROFILE} --cache-control "max-age=2592000" --acl "public-read" --sse "AES256" public/img/ s3://${BUCKET_NAME}/img/
# aws s3 sync --profile ${PROFILE} --cache-control "max-age=2592000" --acl "public-read" --sse "AES256" public/css/ s3://${BUCKET_NAME}/css/
# aws s3 sync --profile ${PROFILE} --cache-control "max-age=2592000" --acl "public-read" --sse "AES256" public/js/ s3://${BUCKET_NAME}/js/

##  Downloads binaries, not part of repo - cache at edge for a year --cache-control "max-age=31536000"
# aws s3 sync --profile ${PROFILE} --cache-control "max-age=31536000" --acl "public-read" --sse "AES256"  static/downloads/ s3://${BUCKET_NAME}/downloads/

## Invalidate landing page so everything sees new post - warning, first 1K/mo free, then 1/2 cent each
aws cloudfront create-invalidation --profile ${PROFILE} --distribution-id ${DISTRIBUTION_ID} --paths "/*"

AWS Guides

AWS CLI - https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html

AWS S3 - https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html

AWS CloudFront - https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/

References

LustForge - https://github.com/twistedpair/lustforge.com/blob/master/deploy_site.sh

{{ template “_internal/disqus.html” . }}


comments powered by Disqus