Automate your Website with Hugo, S3, & CloudFront
February 9, 2019
This is the script I used 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
#### Run this inside your HUGO Directory.
## Make sure you have AWS CLI configured, with a user that has the appropriate permissions.
#### Update these with your code.
DISTRIBUTION_ID=ABCDEF123456 # As pulled from your AWS console.
BUCKET_NAME=ownthe.cloud # Your main bucket that has static hosting checked.
PROFILE=default # Keep as "default" unless you use a separate profile.
hugo -v
#### Copy over Hugo public folder to S3 /w Server Side Encryption (SSE).
# Add ""--exclude 'img' --exclude 'js' --exclude 'downloads' --exclude 'css'"", to the command to control cache behaivor.
aws s3 sync --profile ${PROFILE} --acl "public-read" --sse "AES256" public/ s3://${BUCKET_NAME}/
### (OPTIONAL) 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/
# aws s3 sync --profile ${PROFILE} --cache-control "max-age=31536000" --acl "public-read" --sse "AES256" static/downloads/ s3://${BUCKET_NAME}/downloads/
### Invalidate cache so that everything is up-to-date (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