How would you find the latest AMI programmatically?
IntermediateConceptboto3 & AWS automation
Answer
The cleanest way is the public SSM parameter:
ami = ssm.get_parameter(
Name="/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64")["Parameter"]["Value"]
For your own golden AMIs, filter and sort:
imgs = ec2.describe_images(Owners=["self"], Filters=[{"Name": "tag:Role", "Values": ["web"]}])["Images"]
latest = max(imgs, key=lambda i: i["CreationDate"])["ImageId"]
CreationDate is an ISO string, so lexical max works.
More on boto3 & AWS automation
What is the difference between a boto3 Session, client and resource?BeginnerHow does boto3 find credentials?BeginnerHow does boto3 decide the region, and what is the gotcha with `AWS_REGION`?AdvancedWhy do you need paginators, and how do you use them?BeginnerWhat is JMESPath `search()` on paginators?AdvancedHow do you handle errors from boto3?Beginner