Skip to content

Instantly share code, notes, and snippets.

@edwinakatosh
Last active July 26, 2019 06:08
Show Gist options
  • Save edwinakatosh/6ee8357fc4a66c72c063d381b207f6a3 to your computer and use it in GitHub Desktop.
Save edwinakatosh/6ee8357fc4a66c72c063d381b207f6a3 to your computer and use it in GitHub Desktop.
Gzip static website, upload to S3 and Invalidate cached Cloudfront files
#!/usr/bin/env bash
set -ex
if [ "$#" -ne 1 ]; then
echo "missing bucket name parameter"
exit 1;
fi
BUCKET=$1
if [ ! -d gzip ]; then
mkdir -p gzip;
fi
echo "Running rsync"
rsync -a --delete . gzip --exclude 'gzip' --exclude 's3_gzip_cloudfront.sh' --exclude '.DS_Store'
echo "GZipping files"
find ./gzip \( -iname '*.html' -o -iname '*.css' -o -iname '*.xml' -o -iname '*.js' -o -iname '*.txt' -o -iname '*.js.map' -o -iname '*.css.map' \) \
\! \( -iname 'assets/images' -o -iname 'assets/fonts' \) \
-exec gzip -9 {} \; \
-exec mv {}.gz {} \; \
-exec gzip -t {} \;
echo "Syncing images"
aws s3 sync gzip/assets/images s3://$BUCKET/assets/images --delete --cache-control="max-age=31556926"
echo "Syncing fonts"
aws s3 sync gzip/assets/fonts s3://$BUCKET/assets/fonts --delete --cache-control="max-age=31556926"
echo "Syncing files to S3"
aws s3 sync gzip/ s3://$BUCKET/ --delete --cache-control="max-age=31556926" --content-encoding='gzip' --exclude "assets/images/*" --exclude "assets/fonts/*"
echo "Creating cloudfront cache invalidation"
DISTRIBUTION_ID=$(aws cloudfront list-distributions | jq -r '.[]["Items"][] | select(.DefaultCacheBehavior.TargetOriginId=="S3-"+"'$BUCKET'") | .Id')
aws cloudfront create-invalidation --distribution-id $DISTRIBUTION_ID --paths '/*'
echo "Cleaning up gzip folder"
rm -rf gzip
echo "done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment