Skip to content

Instantly share code, notes, and snippets.

@psa-jforestier
Last active August 27, 2022 01:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psa-jforestier/66b7d5c555f115bc96d17cba82cb833a to your computer and use it in GitHub Desktop.
Save psa-jforestier/66b7d5c555f115bc96d17cba82cb833a to your computer and use it in GitHub Desktop.
Shell script using AWS Cli to purge a CloudFront distribution, by id or by public aliases CNAME
#!/bin/sh
# Always checkout last version from https://github.com/D4UDigitalPlatform/cloudscripts/tree/master/aws/scripts/cloudfront
show_help() {
cat << EOF
Usage:
${0##*/} [--verbose] [--cloudfrontid CLDFID] [--cname CNAME] [--list]
Purge a CloudFront distribution.
options :
--verbose : add more information
--cloudfrontid CLDFID : id of the distribution to purge
--cname CNAME : hostname to purge (ex : www.example.com), will purge the distribution associated to this hostname.
--list : list distribution
EOF
}
print_step() {
echo "==================="
echo "$1"
echo "==================="
}
list_distribution() {
aws cloudfront list-distributions --query 'DistributionList.Items[*].{Id:Id,Status:Status,DomainName:DomainName,ARN:ARN,Aliases:Aliases.Items[*]}' --output table
}
VERBOSE="0"
CLOUDFRONTID=""
CNAME=""
while [[ $1 == * ]]; do
case "$1" in
-h|--help)
show_help
exit 0
;;
--verbose)
VERBOSE=1
;;
--list)
list_distribution
exit
;;
--cloudfrontid)
CLOUDFRONTID="$2"
shift
;;
--cname)
CNAME="$2"
shift
;;
*)
shift
break
;;
esac
shift
done
if [[ "$CLOUDFRONTID" == "" && "$CNAME" == "" ]]; then
show_help
exit 1
fi
if [[ "$CNAME" != "" ]]; then
CLOUDFRONTID=$(aws cloudfront list-distributions --query "DistributionList.Items[?Aliases.Items!=null] | [?contains(Aliases.Items, '$CNAME')].Id | [0]")
if [[ "$CLOUDFRONTID" == "" || "$CLOUDFRONTID" == "null" ]]; then
echo "Unable to find a distribution with a CNAME named $CNAME".
echo "Here are the availble distributions with CNAME :"
list_distribution
exit 1
fi
temp="${CLOUDFRONTID%\"}"
temp="${temp#\"}"
CLOUDFRONTID=$temp
echo "CNAME $CNAME match with distribution $CLOUDFRONTID"
fi
aws configure set preview.cloudfront true
aws cloudfront create-invalidation --distribution-id $CLOUDFRONTID --paths '/*' --output text || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment