Is there a way to list CloudFront distributions by tag without downloading them all using ListDistributions?

Viewed 789

This question is similar, but the only answer there is to get the list of all distributions and filter them locally, which is not what I am looking for.

This page hints that it might be possible to filter by tag ("You can search and filter your resources based on the tags you add"), but I just cannot figure out how!

2 Answers

To add to Balu's great answer, if you have specified a default region when setting up aws-cli and this region is not us-east-1 then it won't work (you'll see an empty array of ResourceTagMappingList).

Be sure to add --region us-east-1 at the end of the command like so:

aws resourcegroupstaggingapi get-resources --tag-filters Key=tagName,Values=tagValue --resource-type-filters 'cloudfront' --tags-per-page 100 --region us-east-1

I can only think of one way, since aws cloudfront doesn't directly support get distributions by tag. we can use resourcegroupstaggingapi cli , to get ResourceARNs of all cloudfront and using jq and sed extract DistributionIds

Ex: Tag ApplicationID=APP1111

aws  resourcegroupstaggingapi get-resources --tag-filters Key=ApplicationID,Values=APP1111 --resource-type-filters 'cloudfront' --tags-per-page 100 | jq -r ".ResourceTagMappingList[].ResourceARN" | sed 's:.*/::'

we can further use xargs and execute get-distribution for each Id.

aws  resourcegroupstaggingapi get-resources --tag-filters Key=ApplicationID,Values=APP1111 --resource-type-filters 'cloudfront' --tags-per-page 100 | jq -r ".ResourceTagMappingList[].ResourceARN" | sed 's:.*/::' | xargs -I {} aws cloudfront  get-distribution --id {}
Related