⚠この記事はブログ移転前のアーカイブです
通常サイトへはこちら
AWS EC2のスポットインスタンスは安くて嬉しいのですが,全データセンターの中で最も安いゾーンを調べるのは骨が折れるのでスクリプト書きました.汚いけど許して
python3.6+ でどうぞ.
リージョンを手動で選択できるとは言え,全データセンターから検索しますからネットワークの品質が重要視される用途には向きません.機械学習等の計算資源を安く手に入れたい人向けです.
boto3が必要です.
# -*- coding: utf_8 -*-
from datetime import datetime, timedelta, timezone
import boto3
## init
aws_key="XXXXXXXXXXKEY"
aws_secret_key="YYYYYYYYYYYYYYYYYYYYYYYYYYSECRET"
instance_types= ['p2.8xlarge']
os_types= ['Linux/UNIX'] # Windows, SUSE Linux...
regions = ['ap-south-1', 'eu-west-2', 'eu-west-1', 'ap-northeast-2', 'ap-northeast-1', 'sa-east-1', 'ca-central-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', ]
history_time = (datetime.now(timezone.utc) + timedelta(hours=-24))
price_list =[]
tmp_list=[]
tmp_list2=[]
## search the price histories and filter the latest price
for re in regions:
print("Seaching " + re)
boto3_session = boto3.session.Session(aws_access_key_id=aws_key,
aws_secret_access_key=aws_secret_key,
region_name=re)
ec2 = boto3_session.client('ec2')
spot_price_history = ec2.describe_spot_price_history(
InstanceTypes=instance_types,
ProductDescriptions=os_types,
StartTime=history_time.isoformat()
)
appended_list = []
for h in spot_price_history.get('SpotPriceHistory'):
tmp_list2=[]
for h2 in spot_price_history.get('SpotPriceHistory'):
if h2['AvailabilityZone'] in appended_list:
pass
elif h['AvailabilityZone'] == h2['AvailabilityZone']:
tmp_list2.append(h2)
tmp = h2
if len(tmp_list2) > 0:
appended_list.append(tmp['AvailabilityZone'])
price_list.append(max(tmp_list2, key=(lambda x :x['Timestamp'])))
print("\n" + str(instance_types)+ "\n-------------------------------\n"+"The availability zone with the most lowest price at all AWS data centers is..." )
print(min(price_list, key=(lambda x :x['SpotPrice'])))
print("\n")
このように動作します.
$ python3 main.py
Seaching ap-south-1
Seaching eu-west-2
Seaching eu-west-1
Seaching ap-northeast-2
Seaching ap-northeast-1
Seaching sa-east-1
Seaching ca-central-1
Seaching ap-southeast-1
Seaching ap-southeast-2
Seaching eu-central-1
Seaching us-east-1
Seaching us-east-2
Seaching us-west-1
Seaching us-west-2
['p2.8xlarge']
-------------------------------
The availability zone with the most lowest price at all AWS data centers is...
{'AvailabilityZone': 'ap-northeast-2c', 'InstanceType': 'p2.8xlarge', 'ProductDescription': 'Linux/UNIX', 'SpotPrice': '10.400600', 'Timestamp': datetime.datetime(2017, 12, 5, 1, 49, 31, tzinfo=tzutc())}
p2.8xlarge ソウルのデータセンターが最も安いようですね.
AWSのAPIキーが必要です.APIキーはIAMで作ることが出来ます.
https://console.aws.amazon.com/iam/home
EC2のスポットインスタンスの価格取得が可能なロールを設定してください.
- aws_key にAWSのAPIキーを入れてください
- aws_secret_keyはAWS APIキーのシークレットの方を
- instance_typesは検索したいインスタンスタイプ1種類
- c4.xlarge
- p2.2xlarge
- r4.8xlarge
- ti.micro
- などなど.
- os_types= [‘Linux/UNIX’]
- Windows
- SUSE Linux
- などなど
パラメータの詳しい種類などはここを参照
http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-spot-price-history.html