Last active
October 30, 2020 01:41
-
-
Save gurunars/59baa52297b3e7b405fec2b9a1f58375 to your computer and use it in GitHub Desktop.
AWS lambda function to find the latest Amazon AMI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Publish the function to S3: | |
cd $DIR_WITH_THIS_SCRIPT | |
zip find_latest_ami_name.zip find_latest_ami_name.py | |
aws s3 cp find_latest_ami_name.zip s3://$YOUR_S3_BUCKET/find_latest_ami_name.zip | |
""" | |
import json | |
import boto3 | |
ARCH_TO_AMI_NAME_PATTERN = { | |
# Architecture: (pattern, owner) | |
"PV64": ("amzn-ami-pv*.x86_64-ebs", "amazon"), | |
"HVM64": ("amzn-ami-hvm*.x86_64-gp2", "amazon"), | |
"HVMG2": ("amzn-ami-graphics-hvm-*x86_64-ebs*", "679593333241") | |
} | |
def find_latest_ami_name(region, arch): | |
assert region, "Region is not defined" | |
assert arch, "Architecture is not defined" | |
assert arch in ARCH_TO_AMI_NAME_PATTERN, \ | |
"Architecture must be one of {}".format( | |
ARCH_TO_AMI_NAME_PATTERN.keys()) | |
pattern, owner = ARCH_TO_AMI_NAME_PATTERN[arch] | |
ec2 = boto3.client("ec2", region_name=region) | |
images = ec2.describe_images( | |
Filters=[dict( | |
Name="name", | |
Values=[pattern] | |
)], | |
Owners=[owner] | |
).get("Images", []) | |
assert images, "No images were found" | |
sorted_images = sorted(images, key=lambda image: image["Name"], | |
reverse=True) | |
latest_image = sorted_images[0] | |
return latest_image["ImageId"] | |
def handler(event, context): | |
props = event.get("ResourceProperties", {}) | |
region = props.get("Region") | |
arch = props.get("Architecture") | |
return find_latest_ami_name(region, arch) | |
if __name__ == "__main__": | |
print find_latest_ami_name("us-east-1", "HVM64") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment