Skip to content

Instantly share code, notes, and snippets.

@bsiegel
Created February 25, 2016 00:15
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 bsiegel/e3841c9f2c243a1b9a68 to your computer and use it in GitHub Desktop.
Save bsiegel/e3841c9f2c243a1b9a68 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib, json, re, os, subprocess, sys, getopt
REGION=0; RELEASE=1; ARCH=3; TYPE=4; URL=6
TABLE_URL = "https://cloud-images.ubuntu.com/locator/ec2/releasesTable"
def usage():
print 'Usage: find_ami.py [options]'
print ''
print 'Options:'
print '\t-h, --help\tThis message'
print '\t-r, --region\tAWS region (default: us-east-1)'
print '\t-v, --release\tUbuntu release (default: trusty)'
print '\t-a, --arch\tArchitecture (default: amd64)'
print '\t-t, --type\tInstance type (default: hvm:instance-store)'
print '\t--terraform\tFormat output as a series of Terraform \'-var\' flags'
try:
opts, args = getopt.getopt(sys.argv[1:], "hr:v:a:t:", ["help", "region=", "release=", "arch=", "type=", "terraform"])
except getopt.GetoptError as err:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
region_arg = 'us-east-1'
release_arg = 'trusty'
arch_arg = 'amd64'
type_arg = 'hvm:instance-store'
tf_format = False
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-r", "--region"):
region_arg = a
elif o in ("-v", "--release"):
release_arg = a
elif o in ("-a", "--arch"):
arch_arg = a
elif o in ("-t", "--type"):
type_arg = a
elif o in ("--terraform"):
tf_format = True
else:
assert False, "unhandled option"
response = urllib.urlopen(TABLE_URL)
data = json.loads(re.sub(r'\n',r'',response.read()).replace('],]',']]'))
if tf_format:
output = []
matches = [[elem[REGION], elem[TYPE], elem[URL]] for elem in data['aaData'] if elem[RELEASE] == release_arg and elem[ARCH] == arch_arg and elem[TYPE].startswith('hvm')]
if not matches:
sys.exit(1)
for result in matches:
match = re.search(r'>(.+)<', result[2])
if match and match.group(1):
output.append("-var 'ami_%s.%s=%s'" % (result[1].replace('hvm:','').replace('-','_'), result[0], match.group(1)))
print " ".join(output)
else:
matches = [elem[URL] for elem in data['aaData'] if elem[REGION] == region_arg and elem[RELEASE] == release_arg and elem[ARCH] == arch_arg and elem[TYPE] == type_arg]
if not matches:
sys.exit(1)
match = re.search(r'>(.+)<', matches[0])
if match and match.group(1):
print match.group(1)
else:
sys.exit(1)
#!/bin/sh
terraform $* $(find_ami.py --terraform)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment