While Ritik Patni's answer was closest to what I needed, I had interpreted the following to mean that I could substitute the bucket name and filter out the CF distribution I was looking for:
[?origin=='S3-BUCKET_NAME']
I did not find this to be the case, as when I created the resource in TF, I used a different name than the bucket name to distinguish between variables. In my case, Origins.Items[0].Id
was staticsite_s3_bucket
, which differed from the name of the s3 bucket, dev-it-static-site-mvp
. So an empty-set was returned.
I was doing this inside of Jenkins, and had a little difficulty with the console output looking like it was misinterpreting quotes, so I'm posting the sh script taken out of the pipeline here, in case the actual implementation can help anyone. Note that Jenkins may not be behaving as it would out-of-the-box. The solution worked in Cloudbees Jenkins Enterprise v 2.249.3.1-rolling.
Also of interest is that I'm referencing the domain name of the s3 bucket to match to the bucket name. AFAIK, this is a safe assumption with buckets not configured with static website hosting. But your mileage may vary.
sh '''#!/bin/sh
set -e
set -x
bucket_name="${ENVIRONMENT}-it-${APP_NAME}"
aws s3 ls ${bucket_name}
aws cloudfront list-distributions
echo "Getting CF distributions matching ${bucket_name} ?"
distributions=$(aws cloudfront list-distributions --query "DistributionList.Items[*].{id:Id,origin_domain:Origins.Items[0].DomainName}[?starts_with(origin_domain,'${bucket_name}.')].id" --output text)
echo ${distributions}
for id in "${distributions}"; do aws cloudfront create-invalidation --distribution-id $id --paths "/*";done;
'''
Finally, I also wanted to point out that this URL was very conveniently useful for me to figure out what I was doing incorrectly: https://jmespath.org/. I was able to paste the raw contents of aws cloudfront list-distributions
and poke around at it until I figured out why I was getting an empty return.