I wanted to fetch the latest ami id for AWS Linux machine while creating an ec2 instance for an autoscaling architecture.
I was trying the aws
cli to get the images types, but it would print out a lot of information if I used the describe-images
command.
My requirement was to get only the image id, so that I could use it to create a launch configuration or launch an instance with the latest ami-id.
A little-known recent feature is the ability to Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog.
The namespace is made up of two parts:
/aws/service/ami-amazon-linux-latest/
These:
aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn*" --query 'sort_by(Images, &CreationDate)[].Name'
Get-EC2ImageByName -Name amzn* | Sort-Object CreationDate | Select-Object Name
can be changed into:
aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --region us-east-1
Get-SSMParameter -Name /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 -region us-east-1
Plus, it can be used in a CloudFormation 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