tor*_*nge 1 amazon-ec2 amazon-web-services python-3.x boto3
现在AWS有一个Pricing API,如何使用Boto3来获取给定的按需 EC2 实例类型(例如t2.micro),区域(例如eu-west-1)和操作系统(例如Linux )的当前每小时价格)?我只想要退回价格.根据我的理解,拥有这四条信息应该足以过滤到单一的结果.
但是,我见过的所有示例都从API获取大量数据,这些数据必须经过后处理才能得到我想要的结果.我希望在返回之前过滤API端的数据.
tor*_*nge 10
这是我最终得到的解决方案.使用Boto3自己的Pricing API以及实例类型,区域和操作系统的过滤器.API仍会返回大量信息,因此我需要进行一些后期处理.
import boto3
import json
from pkg_resources import resource_filename
# Search product filter
FLT = '[{{"Field": "tenancy", "Value": "shared", "Type": "TERM_MATCH"}},'\
'{{"Field": "operatingSystem", "Value": "{o}", "Type": "TERM_MATCH"}},'\
'{{"Field": "preInstalledSw", "Value": "NA", "Type": "TERM_MATCH"}},'\
'{{"Field": "instanceType", "Value": "{t}", "Type": "TERM_MATCH"}},'\
'{{"Field": "location", "Value": "{r}", "Type": "TERM_MATCH"}}]'
# Get current AWS price for an on-demand instance
def get_price(region, instance, os):
f = FLT.format(r=region, t=instance, o=os)
data = client.get_products(ServiceCode='AmazonEC2', Filters=json.loads(f))
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 = 'EU (Ireland)'
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
price = get_price(get_region_name('eu-west-1'), 'c5.xlarge', 'Linux')
print(price)
Run Code Online (Sandbox Code Playgroud)
这会很快返回价格.但任何进一步的优化确实会受到赞赏.
| 归档时间: |
|
| 查看次数: |
3302 次 |
| 最近记录: |