Monthly Archives: January 2015

Programmatically get the ec2 spot price for an instance size

This python script will output the spot price for an instance size passed in via a command line arg. This just looks at the east region but can easily be modified for other aws regions.

import sys, urllib, json
try:
    # Get the jsonp spot price data from amazon
    response = urllib.urlopen("http://spot-price.s3.amazonaws.com/spot.js");
    jsonpstr = response.read();
    data = json.loads(jsonpstr[ jsonpstr.index("(") + 1 : jsonpstr.rindex(")") ])
    # Parse it and retrieve the USD price for the instance size passed in arg[1] i.e. m3.xlarge
    reg=filter(lambda x: x["region"]=="us-east", data["config"]["regions"])
    instance = [ y for x in reg[0]["instanceTypes"] for y in x["sizes"] if y["size"]==sys.argv[1] ]
    print filter(lambda x: x["name"]=="linux", instance[0]["valueColumns"])[0]["prices"]["USD"]
except:
    print 0

My python knowledge is very minimal so any suggested improvements would be appreciated.