Remove multiple CloudFront distributions with “aws cli”

Romans Malinovskis
Jul 28 · 2 min read

What will you need?

List your distributions nicely

aws cloudfront list-distributions | jq '.DistributionList.Items[]|[ .Id, .Status, .Origins.Items[0].DomainName, .Aliases.Items[0] ] | @tsv '  -r
E1036CN6S????? Deployed bucket1.s3.amazonaws.com www.example.com
EQS6J3M1?????? Deployed bucket2.s3.amazonaws.com www.foo.com
E269QTGS?????? Deployed bucket2.s3.amazonaws.com www.baz.com

Filtering the list

cat results.txt | awk '$3=="bucket2.s3.amazonaws.com" {print}'
MYENVBUCKET="bucket2.s3.amazonaws.com"
cat results.txt | awk '$3=="'$MYENVBUCKET'" {print}'

Disabling the distributions

cat results.txt | while read id status origin cname; do   echo "About to disable $id (CNAME=$cname)"   # code for disabling goes heredone
tmpfile=$(mktemp /tmp/ms-infra-destroy.XXXXXX)
tmpfile2=$(mktemp /tmp/ms-infra-destroy.XXXXXX)
# Update JSON output by setting Enabled=Falseaws cloudfront get-distribution-config --id $id | jq .DistributionConfig.Enabled=false > $tmpfile# We only need "DistributionConfig"jq -r .DistributionConfig $tmpfile > $tmpfile2aws cloudfront update-distribution --id $id \
--if-match $(jq .ETag $tmpfile -r) \
--distribution-config file://$tmpfile2
rm $tmpfile $tmpfile2

Delete disabled distributions

cat results.txt | while read id status origin cname; do   echo "Waiting to delete $id (CNAME=$cname)"   aws cloudfront wait distribution-deployed --id $id   aws cloudfront delete-distribution --id $id --if-match \
$(aws cloudfront get-distribution-config --id $id | jq .ETag -r)
done
Romans Malinovskis

Written by

London based Web Developer, DevOps, Author of https://agiletoolkit.org.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade