In this post we will show you how do reference latest Amazon Linux IDs using AWS Systems Manger Parameter Store? and using with AWS CloudFormation template.
In example template:
# Use public Systems Manager Parameter Parameters: LatestAmiId: Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>' Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2' Resources: Instance: Type: 'AWS::EC2::Instance' Properties: ImageId: !Ref LatestAmiId
Querying for the latest AMI using public parameters:
After you have your target namespace, your query can be created to retrieve the latest Amazon Linux AMI ImageID value. Each Region has an exact replica namespace containing its Region-specific ImageID value.
Using the AWS CLI:
aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --region eu-west-1
Always launch new instances with the latest ImageID:
After you have created the query, you can embed the command as a command substitution into your new instance launches.
Using the AWS CLI:
aws ec2 run-instances --image-id $(aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --query 'Parameters[0].[Value]' --output text) --count 1 --instance-type t2.micro
This new instance launch always results in the latest publicly available Amazon Linux AMI for amzn2-ami-hvm-x86_64-gp2. Similar embedding can be used in a number of automation process, docs, and coding languages.
Display a complete list of all available Public Parameter Amazon Linux AMIs:
You can also query for the complete list of AWS Amazon Linux Parameter Store namespaces available.
aws ssm get-parameters-by-path --path "/aws/service/ami-amazon-linux-latest" --region eu-west-1
/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 /aws/service/ami-amazon-linux-latest/amzn2-ami-minimal-hvm-x86_64-ebs /aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-ebs /aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-s3
Each Amazon Linux AMI now has its own Parameter Store namespace that is public and describable. Upon querying, an AMI namespace returns only its regional ImageID value.
The namespace is made up of two parts:
Parameter Store Prefix (tree): /aws/service/ami-amazon-linux-latest/
AMI name alias: (example) amzn-ami-hvm-x86_64-gp2
You can determine an Amazon Linux AMI alias by taking the full AMI name property of an Amazon Linux public AMI and removing the date-based version identifier. A list of these AMI name properties can be seen by running one for the following Amazon EC2 queries.
aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn*" --query 'sort_by(Images, &CreationDate)[].Name'