Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Deploy changed assets to S3 and generate a CloudFront invalidation.
#!/bin/bash
set -e
# must set BUCKET and CLOUDFRONT_DIST_ID environment variables
PROJECT_BASE=$(cd "$(dirname "$0")/../" && pwd)
# change directories into project base
cd "$PROJECT_BASE"
# this script deploys changed assets to S3 and creates and awaits an invalidation to CloudFront
upload_result_file=$(mktemp)
modified_file=$(mktemp)
invalidation_result_file=$(mktemp)
function cleanup() {
rm $upload_result_file $modified_file $invalidation_result_file
}
function fail() {
cleanup
echo ERROR: $@ >&2
exit 1
}
# sanity check utility presence
which aws >/dev/null || fail "AWS CLI not found."
which jq >/dev/null || fail "jq not found."
# sanity check bucket and cloudfront definition
if [ -z "$BUCKET" ]; then
fail "BUCKET environment variable not defined."
fi
if [ -z "$CLOUDFRONT_DIST_ID" ]; then
fail "CLOUDFRONT_DIST_ID environment variable not defined."
fi
# enable cloudfront preview if it's not already enabled
if [[ "$(aws configure get preview.cloudfront)" != "true" ]]; then
echo "Enabling AWS CloudFront Preview Support."
aws configure set preview.cloudfront true
echo
fi
# upload changed files
echo "Syncing assets to S3..."
aws s3 sync --sse AES256 site/ s3://$BUCKET/ | tee $upload_result_file
echo
# gather a list of changed files for invalidation
cat $upload_result_file | grep -oP '(?<=upload: ).+(?= to )' | sed 's:^site/::' \
> $modified_file
# if no files were modified, just exit out
if [[ $(cat $modified_file | wc -l) -eq 0 ]]; then
echo "No files modified, nothing to do."
cleanup
exit 0
fi
# start the invalidation; note: paths must be prefixed with slash
echo "Creating CloudFront Invalidation..."
cat $modified_file | sed 's:^:/:g' | xargs -t -I {} --no-run-if-empty \
aws cloudfront create-invalidation --distribution-id $CLOUDFRONT_DIST_ID \
--paths {} | tee $invalidation_result_file
echo
# extract the invalidation id
invalidation_id=$(jq -r '.Invalidation.Id' $invalidation_result_file)
echo "Invalidation $invalidation_id Created."
echo
cleanup
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment