能否通过AWS CLI或PowerShell SDK按标签获取CloudFront分发ID?
Retrieve CloudFront Distribution ID by Tag Using AWS CLI
Yep, you absolutely can fetch CloudFront Distribution IDs based on tag values using the AWS CLI combined with jq for JSON parsing—no need to rely solely on resource ARNs anymore. Here's a practical solution tailored to your scenario:
Approach Breakdown
- First, we grab all CloudFront distribution ARNs with the
list-distributionscommand - Loop through each ARN to fetch its associated tags using
list-tags-for-resource - Check if the tag value (for your specific key
CLIENT_APP) matches your target (likeTEST_APP) - Extract the Distribution ID from the ARN—it's the last 14 characters of the ARN, following CloudFront's standard format
arn:aws:cloudfront::account-id:distribution/DIST_ID
Working Script
# Set your target tag value here (e.g., the TEST_APP value from your tag result) TARGET_TAG_VALUE="TEST_APP" # Fetch all CloudFront distribution ARNs cloudfront_arns=$(aws cloudfront list-distributions | jq -r ".DistributionList.Items[].ARN") # Loop through each ARN to check tags for arn in $cloudfront_arns do # Get the value of the CLIENT_APP tag for this distribution current_tag_value=$(aws cloudfront list-tags-for-resource --resource "$arn" | jq -r '.Tags.Items[] | select(.Key == "CLIENT_APP").Value') # Match against our target value if [ "$current_tag_value" == "$TARGET_TAG_VALUE" ] then # Extract the Distribution ID from the end of the ARN CLOUDFRONT_DISTRIBUTION_ID="${arn:(-14)}" echo "Matching Distribution ID found: $CLOUDFRONT_DISTRIBUTION_ID" # Uncomment below if you only need the first matching ID and want to stop the loop early # break fi done
Notes
- I tweaked the
jqfilter to specifically target theCLIENT_APPkey—this prevents false matches if other tags happen to share the same value as your target. - If you expect multiple distributions to have the same tag value, remove the
breakcomment to list all matching IDs. - Make sure you have
jqinstalled on your system (it's a common JSON parsing tool for CLI workflows).
内容的提问来源于stack exchange,提问作者Elnur Mammadov
相关产品推荐
相关产品推荐

