Created
March 9, 2017 15:07
-
-
Save benton/95889148a9dc75cbf5f5eb609045b331 to your computer and use it in GitHub Desktop.
Fetch latest Canonical Ubuntu AMI ID for a given region
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
require 'aws-sdk-resources' | |
require 'diskcached' | |
# ... | |
CANONICAL_AWS_ID = '099720109477' # AWS ID for Ubuntu's publisher | |
DATE_MATCHER = /(\d\d\d\d)(\d\d)(\d\d)(\.\d+)?\Z/ | |
# Returns the latest Canonical Ubuntu AMI for a given | |
# Ubuntu version, AWS region, architecture, and root device type. | |
def latest_ubuntu_ami(ubuntu_version, region = 'us-east-1', | |
arch = 'x86_64', root_type = 'ebs', vm_type = "hvm") | |
ec2 = Aws::EC2::Resource.new(region: region) | |
cache_key = [ubuntu_version, region, arch, root_type, vm_type].join('-') | |
diskcache = Diskcached.new(File.join(PROJECT_DIR, 'tmp', 'AMIcache')) | |
diskcache.cache(cache_key) do | |
candidates = ec2.images(owners: [CANONICAL_AWS_ID]).select do |image| | |
# (image.type == :machine) && | |
(image.root_device_type == root_type) && | |
(image.architecture == arch) && | |
(image.virtualization_type == vm_type) && | |
((image.name || '') =~ DATE_MATCHER) && | |
((image.name || '') =~ /#{ubuntu_version}/) | |
end | |
candidates.sort{|a,b| a.name <=> b.name}.last.id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment