Skip to content

Instantly share code, notes, and snippets.

@elleryq
Last active August 19, 2016 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elleryq/387b8777237557e20ab333837ea28e67 to your computer and use it in GitHub Desktop.
Save elleryq/387b8777237557e20ab333837ea28e67 to your computer and use it in GitHub Desktop.
ubuntu ami locator
"""
Ubuntu AMI locator
Example:
images = ubuntu_ami_locator()
images = ubuntu_ami_locator(zone=u'us-west-2', virtualization_type=u'hvm')
Reference:
* https://github.com/jspiro/node-ubuntu-ami-locator
"""
# -*- coding: utf-8 -*-
from collections import namedtuple
from urlparse import urljoin
import requests
CloudImage = namedtuple('CloudImage', [
'suite', 'stream', 'tag', 'release', 'instance_type', 'arch', 'zone',
'ami_id', 'aki_id', 'unused', 'virtualization_type'])
def ubuntu_ami_locator(**kwargs):
# Query URLs resolve to text files and are built like so:
# https://cloud-images.ubuntu.com/query/<suite>/<stream>/<query_file>
# E.g.
# https://cloud-images.ubuntu.com/query/precise/server/released.current.txt
tag = kwargs.pop('tag', 'release')
if tag and tag == 'release':
tag = 'released'
current = kwargs.pop('current', 'current')
query_file = '{tag}.{current}.txt'.format(
tag=tag, current=current)
stream = kwargs.pop('stream', 'server')
suite = kwargs.pop('suite', 'trusty')
base_url = "https://cloud-images.ubuntu.com/query/"
endpoint = urljoin(base_url, '/'.join([suite, stream, query_file]))
r = requests.get(endpoint)
lines = r.text.split('\n') # csv format
cloud_images = []
for line in lines:
if not line:
continue
cloud_images.append(
CloudImage._make(line.split('\t')))
if kwargs:
def _func(cloud_image):
match = True
for key, value in kwargs.items():
prop_value = getattr(cloud_image, key)
if value != prop_value:
match = False
break
return match
result = filter(_func, cloud_images)
else:
result = cloud_images
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment