Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active October 19, 2023 11:22
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magnetikonline/e822a78a9b691d86d6e45626f8f0c977 to your computer and use it in GitHub Desktop.
Save magnetikonline/e822a78a9b691d86d6e45626f8f0c977 to your computer and use it in GitHub Desktop.
List AWS AMI IDs for a given marketplace product URL.

List AWS AMI IDs for a given marketplace product

Script to return AMI IDs for a given AWS region associated to a marketplace product page. Requires AWS CLI and a valid set of credentials for the aws ec2 describe-images call.

Usage

  • Browse the AWS marketplace to locate the product of interest.

  • Note the URL of the product page.

  • Execute script for the desired region:

     $ ./listmarketplaceami.sh ap-southeast-2 "https://aws.amazon.com/marketplace/pp/B00UU272MM"
     # ami-07b6ae8cccab5644b:2020-08-24T18:38:46.000Z:NGINX Plus - Amazon Linux AMI (HVM, v1.4), provided by Nginx, Inc.

Reference

#!/bin/bash -e
MARKETPLACE_URL_REGEXP="^https://aws.amazon.com/marketplace/pp/[A-Z0-9]{10}(\?|$)"
MARKETPLACE_HTML_PRODUCTID_REGEXP="/marketplace/fulfillment\?productId=([a-f0-9-]+)"
function exitError {
echo "Error: $1" >&2
exit 1
}
if [[ (-z $1) || (-z $2) ]]; then
echo "Usage: $(basename "$0") REGION MARKETPLACE_URL"
exit 1
fi
# sanity check that marketplace URL given at least looks like one
if [[ ! $2 =~ $MARKETPLACE_URL_REGEXP ]]; then
exitError "the marketplace URL given doesn't appear to be valid"
fi
# fetch product ID from marketplace page source
if [[ ! $(curl --silent "$2") =~ $MARKETPLACE_HTML_PRODUCTID_REGEXP ]]; then
exitError "unable to extract product ID from marketplace page"
fi
# list available AMI entities associated with marketplace product ID
aws ec2 describe-images \
--filters "Name=name,Values=*-${BASH_REMATCH[1]}-*" \
--output text \
--query "reverse(sort_by(Images,&CreationDate))[].[join(':',[ImageId,CreationDate,Description])]" \
--region "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment