Last active
January 5, 2019 10:35
-
-
Save gngdb/f013156a6af184ccbde7f348f894f629 to your computer and use it in GitHub Desktop.
Where in the world is Carmen Sandiego? If "Carmen Sandiego" is the cheapest spot price on AWS EC2:
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 | |
class Session(boto3.Session): | |
def __enter__(self): | |
return self | |
def __exit__(self, *args): | |
del self | |
with Session() as sess: | |
# get names of regions | |
client = sess.client('ec2') | |
regions = client.describe_regions() | |
region_names = [r['RegionName'] for r in regions['Regions']] | |
# funtion to get prices for an instance type | |
machine_type_args = dict(InstanceTypes=['m3.medium'], | |
MaxResults=1, | |
ProductDescriptions=['Linux/UNIX (Amazon VPC)']) | |
def read_spot_price(client, zone, **kwargs): | |
prices = client.describe_spot_price_history(AvailabilityZone=zone, **kwargs) | |
return prices['SpotPriceHistory'][0] | |
# iterate over all regions and availability zones | |
zones = {} | |
prices = [] | |
for r in region_names: | |
print(r) | |
with Session(region_name=r) as sess: | |
client = sess.client('ec2') | |
response = client.describe_availability_zones() | |
zones[r] = [r['ZoneName'] for r in response['AvailabilityZones']] | |
for z in zones[r]: | |
try: | |
p = read_spot_price(client, z, **machine_type_args) | |
prices.append((z, p['SpotPrice'])) | |
except IndexError: | |
pass | |
# list zones, sorted by price | |
for z,p in sorted(prices, key=lambda x: x[1], reverse=True): | |
print(z,p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment