Created
June 21, 2012 00:13
-
-
Save johntrimble/2963079 to your computer and use it in GitHub Desktop.
Python script for generating a mapping of regions to the latest AMI for a given Ubuntu distribution and instance type for use in CloudFormation template.
This file contains hidden or 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
#!/usr/bin/env python | |
import urllib2 | |
import json | |
import itertools | |
import sys | |
import argparse | |
def groupby(data, key): | |
kf = lambda x: x[key] | |
result = itertools.groupby(sorted(data,None,kf), kf) | |
return result | |
def find_latest_builds(distro, instance_type): | |
builds = [] | |
# We should use 'with' here, but the object returned by urlopen doesn't have | |
# sufficient awesome. | |
f = urllib2.urlopen("https://cloud-images.ubuntu.com/query/%s/server/daily.current.txt" % distro) | |
try: | |
for l in f: | |
builds.append(dict(zip(['instance_type', 'arch', 'region', 'ami'], l.split()[4:8]))) | |
finally: | |
f.close() | |
return filter(lambda x: x['instance_type'] == instance_type, builds) | |
# Get the arguments | |
parser = argparse.ArgumentParser(description='Generates a mapping of regions to the latest AMI for a given Ubuntu release and instance type for use in a CloudFormation template.') | |
parser.add_argument('distro', type=str, help='code name of Ubuntu distribution (natty, oneiric, precise, etc.)') | |
parser.add_argument('instancetype', type=str, help='EC2 instance type', choices=['instance-store', 'ebs']) | |
args = parser.parse_args() | |
# Pull the builds | |
builds = find_latest_builds(args.distro, args.instancetype) | |
# Create the JSON mapping | |
region_arch_ami_map = { | |
region: { | |
arch: i2.next()['ami'] | |
for arch, i2 in groupby(i, 'arch') | |
} | |
for region, i in groupby(builds, 'region') | |
} | |
print json.dumps(region_arch_ami_map, indent=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment