【发布时间】:2020-03-27 14:45:23
【问题描述】:
使用 Aws 批量定价 API,我只能下载一个区域的 JSON,因此我正在寻找使用 Python 以编程方式获取所有区域的定价详细信息。
提前致谢。
【问题讨论】:
标签: python-3.x amazon-web-services amazon-ec2 boto3
使用 Aws 批量定价 API,我只能下载一个区域的 JSON,因此我正在寻找使用 Python 以编程方式获取所有区域的定价详细信息。
提前致谢。
【问题讨论】:
标签: python-3.x amazon-web-services amazon-ec2 boto3
就像docs中所说的:
import boto3
client = boto3.client('pricing')
response = client.describe_services(
ServiceCode='string',
FormatVersion='string',
NextToken='string',
MaxResults=123
)
你只需要一个包含你想要的区域的环境变量:AWS_DEFAULT_REGION
或者您可以在客户端本身设置区域:
client = boto3.client('pricing', region_name='us-west-2')
不使用boto:
my_region = "us-west-1"
url = f"https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/{my_region}/index.json"
result = requests.get(url)
【讨论】:
以下代码将下载不同地区的按需和预留期限实例定价详细信息并存储到我的本地系统中
import boto3
from boto3.session import Session
import requests
import json
import datetime
s = Session()
ec2AvailableRegions = []
def getAvailableRegionsForAService(serviceName):
try:
if serviceName == "ec2":
global ec2AvailableRegions
ec2AvailableRegions = s.get_available_regions(serviceName)
except Exception as ex:
print(ex)
print("Exception occured while fetching the available region for the service "+serviceName)
getAvailableRegionsForAService('ec2')
print("AmazonEC2 Available Regions : "+str(ec2AvailableRegions))
for region in ec2AvailableRegions:
url = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/{0}/index.json"
url = url.format(region)
print(region)
print(url)
print(datetime.datetime.now())
response = requests.get(url)
open('A:\Office\index'+region+".json", 'wb').write(response.content)
print(datetime.datetime.now())
【讨论】: