A easy way to do this is to execute the query below:
aws ec2 describe-images \
--region us-west-2 \
--owners self \
--filters "Name=name,Values=base-v*-al2023-arm64-*" \
--query 'Images | sort_by(@, &CreationDate) | [-1].ImageId' \
--output text
But if you want to automate this inside a shell script, here what you can do:
# Get the latest AMI ID
region="us-west-2"
AMI_PATTERN="base-v*-al2023-arm64-*"
LATEST_AMI_ID=$(aws ec2 describe-images \
--region $region \
--owners self \
--filters "Name=name,Values=$AMI_PATTERN" \
--query 'Images | sort_by(@, &CreationDate) | [-1].ImageId' \
--output text)
# Check if an AMI ID was found
if [ "$LATEST_AMI_ID" == "None" ]; then
echo "No AMI found with the pattern: $AMI_PATTERN"
exit 1
fi
# Now simply use it, for example to create a CloudFormation Stack with the latest private AMI ID:
stack-name="cfn-create-ec2-latest-ami-test"
profile="do-use2-prd"
aws cloudformation update-stack \
--stack-name $stackname \
--template-body file:///Users/devops/Documents/Github/devops/cloudformation/cfn-test.yaml \
--capabilities CAPABILITY_NAMED_IAM \
--parameters ParameterKey=LatestAmiId,ParameterValue=$LATEST_AMI_ID \
--region $region \
--profile $profile \
--output json
Enjoy 😉