Use latest AMIs by dynamically referencing SSM Parameter Store in your CloudFromation templates

CloudFormation templates with the following will select the latest AMI IDs directly from SSM Parameter store to deploy the instance.

Adding inline in Resources of the template

Resources:
  Instance: 
    Type: AWS::EC2::Instance
    Properties:
      ImageId: '{{resolve:ssm:/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id}}'

Adding in Parameters of the template

Parameters:
  ImageId: 
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id'
Resources:
  Instance: 
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Ref ImageId

Looking up the parameter using AWS CLI

$ aws ssm get-parameter --name /aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id
{
    "Parameter": {
        "Name": "/aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id",
        "Type": "String",
        "Value": "ami-0c7217cdde317cfec",
        "Version": 44,
        "LastModifiedDate": "2023-12-07T03:47:04.175000+00:00",
        "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id",
        "DataType": "aws:ec2:image"
    }
}
$ aws ssm get-parameter --name /aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id
{
    "Parameter": {
        "Name": "/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id",
        "Type": "String",
        "Value": "ami-0c9db8d36d76d38ed",
        "Version": 126,
        "LastModifiedDate": "2023-12-05T17:35:14.150000+00:00",
        "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id",
        "DataType": "text"
    }
}
$ aws ssm get-parameter --name /aws/service/marketplace/prod-tdzx6newyhgcc/6.4.1-6-r13-on-debian-11
{
    "Parameter": {
        "Name": "/aws/service/marketplace/prod-tdzx6newyhgcc/6.4.1-6-r13-on-debian-11",
        "Type": "String",
        "Value": "ami-04e81d256e77d2116",
        "Version": 6,
        "LastModifiedDate": "2023-11-22T20:59:53.391000+00:00",
        "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/marketplace/prod-tdzx6newyhgcc/6.4.1-6-r13-on-debian-11",
        "DataType": "text"
    }
}