Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch latest Canonical Ubuntu AMI ID for a given region
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