Created
February 3, 2018 16:56
-
-
Save Julian/20ddcc51452cd430cf76c9a9cfafdfa2 to your computer and use it in GitHub Desktop.
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
from collections import defaultdict | |
from datetime import datetime, timedelta | |
from decimal import Decimal | |
from pprint import pformat, pprint | |
import json | |
import boto3 | |
import requests | |
with requests.get("http://www.ec2instances.info/instances.json") as response: | |
vCPUs = { | |
instance["instance_type"]: instance["vCPU"] | |
for instance in response.json() | |
} | |
clients = { | |
region["RegionName"]: boto3.client("ec2", region_name=region["RegionName"]) | |
for region in boto3.client( | |
"ec2", region_name="us-east-1", | |
).describe_regions()["Regions"] | |
if region["RegionName"].startswith(("us-east", "us-west")) | |
} | |
availability_zones = { | |
region: { | |
zone["ZoneName"] | |
for zone in client.describe_availability_zones()["AvailabilityZones"] | |
} for region, client in clients.iteritems() | |
} | |
price_per_vCPU = {} | |
for instance, vCPU in vCPUs.iteritems(): | |
price_per_vCPU[instance] = {} | |
for region, client in clients.iteritems(): | |
price_per_vCPU[instance][region] = region_prices = {} | |
for zone in availability_zones[region]: | |
history = client.describe_spot_price_history( | |
InstanceTypes=[instance], | |
AvailabilityZone=zone, | |
ProductDescriptions=["Linux/UNIX (Amazon VPC)"], | |
MaxResults=1, | |
StartTime=datetime.utcnow() - timedelta(hours=1), | |
)["SpotPriceHistory"] | |
if history: | |
price, = history | |
region_prices[zone] = Decimal(price["SpotPrice"]) / vCPU | |
top_3 = sorted( | |
(price, zone) for zone, price in region_prices.iteritems() | |
)[:3] | |
if not top_3: | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment