Skip to content

Instantly share code, notes, and snippets.

@Agoreddah
Created May 22, 2019 14:30
Show Gist options
  • Save Agoreddah/1f95ef92c8a37cd875338edfe38e783b to your computer and use it in GitHub Desktop.
Save Agoreddah/1f95ef92c8a37cd875338edfe38e783b to your computer and use it in GitHub Desktop.
AWS Cloudfront (CDN) invalidation script
#!/bin/bash
#================================================================
# HEADER
#================================================================
#% SYNOPSIS
#+ ${SCRIPT_NAME} --distributionId "argument" [--help]
#%
#% DESCRIPTION
#% Function to run AWS CDN invalidation and finishes when invalidation status is set to Completed. Invalidation path is set to '/*' by default.
#%
#% OPTIONS
#% --distributionId Id of Cloudfront distribution where invalidation will begin
#% --help Print this help
#%
#% EXAMPLES
#% ${SCRIPT_NAME} --distributionId <id>
#%
#================================================================
#- version 0.0.1
#================================================================
# END_OF_HEADER
#================================================================
SCRIPT_HEADSIZE=$(head -200 ${0} |grep -n "^# END_OF_HEADER" | cut -f1 -d:)
SCRIPT_NAME="$(basename ${0})"
run_help() {
head -${SCRIPT_HEADSIZE:-99} ${0} | grep -e "^#[%+-]" | sed -e "s/^#[%+-]//g" -e "s/\${SCRIPT_NAME}/${SCRIPT_NAME}/g" ;
}
HELP=0
cecho(){
RED="\033[0;31m"
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
printf "${!1}${2} ${NC}\n"
}
for i in "$@"
do
case $i in
--distributionId)
shift
if [ -z "$1" ]
then
cecho "RED" "Distribution ID cannot be empty"
exit 1
else
DISTRIBUTION_ID="$1"
fi
shift
;;
--help)
HELP=1
run_help
shift
;;
-*)
cecho "RED" "Error: Unknown option: $1" >&2
run_help
exit 1
esac
done
get_invalidation_status(){
invalidation=$1
distribution=$2
status=$(
${AWS} cloudfront \
get-invalidation --id "${invalidation}" \
--distribution-id "${distribution}" \
--query Invalidation.Status \
--output text
)
echo "${status}"
}
run_command () {
cecho "GREEN" "Running cdn invalidation for Distribution ID: ${DISTRIBUTION_ID}"
AWS=aws
INVALIDATION_ID=$( ${AWS} cloudfront create-invalidation \
--distribution-id "${DISTRIBUTION_ID}" \
--paths '/*' \
--query Invalidation.Id \
--output text
)
while true; do
STATUS=$(get_invalidation_status "${INVALIDATION_ID}" "${DISTRIBUTION_ID}")
DATETIME=$(date +%H:%M:%S)
echo "-------------------------"
echo "Distribution: ${DISTRIBUTION_ID}"
echo "Invalidation: ${INVALIDATION_ID}"
echo "Status: ${STATUS}"
echo "Time:" ${DATETIME}
echo "-------------------------"
if [ "${STATUS}" == "Completed" ];
then
cecho "GREEN" "Completed !"
break
fi
sleep 10
done
}
if [ "${HELP}" != 1 ];
then
if [ -z "${DISTRIBUTION_ID}" ];
then
cecho "RED" "Distribution Id is missing !"
exit 1
else
run_command
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment