Created
May 25, 2021 09:12
-
-
Save JamesWoolfenden/16a0e8f0bbaac9172b0c8b36d8afa92c to your computer and use it in GitHub Desktop.
example of using the aws pricing api
This file contains 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
import boto3 | |
import json | |
from pkg_resources import resource_filename | |
product_filters = [ | |
{'Type': 'TERM_MATCH', | |
'Field': 'volumeType', | |
'Value': 'General Purpose'} | |
] | |
# Get current AWS price for an on-demand instance | |
def get_price(region, instance, os): | |
data = client.get_products(ServiceCode='AmazonEC2', Filters=product_filters) | |
od = json.loads(data['PriceList'][0])['terms']['OnDemand'] | |
id1 = list(od)[0] | |
id2 = list(od[id1]['priceDimensions'])[0] | |
return od[id1]['priceDimensions'][id2]['pricePerUnit']['USD'] | |
# Translate region code to region name | |
def get_region_name(region_code): | |
default_region = 'Europe (London)' | |
endpoint_file = resource_filename('botocore', 'data/endpoints.json') | |
try: | |
with open(endpoint_file, 'r') as f: | |
data = json.load(f) | |
return data['partitions'][0]['regions'][region_code]['description'] | |
except IOError: | |
return default_region | |
# Use AWS Pricing API at US-East-1 | |
client = boto3.client('pricing', region_name='us-east-1') | |
# Get current price for a given instance, region and os | |
region_str=get_region_name('eu-west-2') | |
price = get_price(get_region_name('eu-west-2'), 'c5.xlarge', 'Linux') | |
print(price) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment