REST API - AWS EC2 每小时定价



我想以编程方式检索 AWS EC2 实例的给定实例 ID 的价格列表。 我正在尝试通过普通的 REST API 调用(即没有框架(来做到这一点。

我想提供一个实例 ID 列表:

i-12345   
i-45678
...

并最终检索其每小时价格:

i-12345 = $0.032
i-45678 = $0.56
...

我正在尝试将 Postman 与我的AccessKeySecretKey一起使用,但在使用时会得到401 Unauthorizedhttps://ec2.amazonaws.com/?Action=DescribeInstances&Filter.1.Name=instance-id&Filter.1.Value=i-12345

很可能我需要多个 REST 调用:

  1. 描述实例以获取实例大小和区域。
  2. 调用定价终结点https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/Welcome.html

有什么想法吗?

笔记:

  • 我知道价目表JSONhttps://aws.amazon.com/blogs/aws/new-aws-price-list-api/但这篇文章来自2015年。

  • 我知道 JSON 下载https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/us-east-1/index.json但这需要我首先知道我的每个实例在哪个区域运行,然后为每个区域下载整个 +20MB JSON。

  • 我知道定价页面:https://aws.amazon.com/ec2/pricing/它突出了另一个复杂性 -实例是如何创建的。

也许我走错了路。也许我应该查询cost explorer API以查看实例在过去 X 天内的成本,从而从中推断?

有一个定价API,请参阅Jeff Barr的博客: https://aws.amazon.com/blogs/aws/aws-price-list-api-update-new-query-and-metadata-functions/

请注意,定价记录适用于多种服务,因此一个好的过滤器确实可以帮助您放大您返回的记录以及所需的分页 API 调用数量(转化为速度......

例:

b3session = boto3.Session(region_name="us-east-1") # pricing API not supported in all regions, I default to us-east-1
pricing_client = b3session.client('pricing')
# Filter to only on-demand, no pre-isntalled SW, and Linux (to avoid adding OS cost in this example)
region_name = 'eu-west-1'
query_parameters =  {           
'ServiceCode': 'AmazonEC2',
'FormatVersion': 'aws_v1',
'Filters': [
{"Type": "TERM_MATCH", "Field": "regionCode", "Value": region_name},
{"Type": "TERM_MATCH", "Field": "marketoption", "Value": "OnDemand"},
{"Type": "TERM_MATCH", "Field": "preInstalledSw", "Value": "NA"},
{"Type": "TERM_MATCH", "Field": "operatingSystem", "Value": "Linux"},
{"Type": "TERM_MATCH", "Field": "productFamily", "Value": "Compute Instance"},
{"Type": "TERM_MATCH", "Field": "tenancy", "Value": "Shared"},
]
}   
next_token = True
while next_token:
try:
prices = pricing_client.get_products(**query_parameters)
except Exception as e:
print("Some thing went wrong)
exit(1)
if 'NextToken' in prices.keys():
query_parameters['NextToken'] = prices['NextToken']
else:
next_token = False
for p in prices["PriceList"]:
price = json.loads(p).   # (This API returns strings, not dicts)
## DO SOMETHING WITH THIS PRICING RECORD

最新更新