Search This Blog

Friday, October 18, 2013

Get Amazon EC2 instance price in a program

 Although the json file in the url does not include RHEL, SUSE, Windows with SQL instances, this would be useful for most of cases.


-----------------------------------


 import json
 import urllib2


type_translation = {
 ('stdODI', 'sm'):   'm1.small'  ,
 ('stdODI', 'med'):  'm1.medium' ,
 ('stdODI', 'lg'):   'm1.large' ,
 ('stdODI', 'xl'):   'm1.xlarge' ,
 ('uODI', 'u'):   't1.micro' ,
 ('hiMemODI', 'xl'):   'm2.xlarge' ,
 ('hiMemODI', 'xxl'):   'm2.2xlarge' ,
 ('hiMemODI', 'xxxxl'):   'm2.4xlarge' ,
 ('secgenstdODI', 'xl'):   'm3.xlarge' ,
 ('secgenstdODI', 'xxl'):   'm3.2xlarge' ,
 ('hiCPUODI', 'med'):   'c1.medium' ,
 ('hiCPUODI', 'xl'):   'c1.xlarge' ,
 ('clusterComputeI', 'xxxxl'):   'cc1.4xlarge' ,
 ('clusterComputeI', 'xxxxxxxxl'):   'cc2.8xlarge' ,
 ('clusterHiMemODI' , 'xxxxxxxxl'):   'cr1.8xlarge' ,
 ('clusterGPUI', 'xxxxl'):   'cg1.4xlarge' ,
 ('hiIoODI', 'xxxxl')  : 'hi1.4xlarge' ,
 ('hiStoreODI', 'xxxxxxxxl') :'hs1.8xlarge'
}
region_translation = {
 'us-east': 'us-east-1',
 'us-west-2' :'us-west-2',
 'us-west' :'us-west-1',
 'eu-ireland':'eu-west-1',
 'apac-sin':'ap-southeast-1',
 'apac-syd': 'ap-southeast-2',
 'apac-tokyo':'ap-northeast-1',
 'sa-east-1':'sa-east-1'
}


instance_price={}

def getprice():
        response = urllib2.urlopen('http://aws.amazon.com/ec2/pricing/pricing-on-demand-instances.json')
        pricejson = response.read()
        pricing = json.loads(pricejson)

        for region in pricing['config']['regions']:
                for itypes in region['instanceTypes']:
                        for size in itypes['sizes']:
                                for column in size['valueColumns']:
                                        instance_price[region_translation[region['region']],type_translation[(itypes['type'], size['size'])], column['name']]=column['prices']['USD']