Automate your Website with Hugo, S3, & CloudFront

Bash script to load Hugo Site to S3 bucket and invalidate Cloudfront cache

Cole Russell
February 9, 2020

Bash Script to Update S3 and invalidate Cloudfront

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.

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.     # 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 Config

AWS S3 Website Hosting

AWS CloudFront with Static Website


LustForge -