【问题标题】:How to get the AmazonEC2 instances pricing details for different regions using boto3 in python如何在 python 中使用 boto3 获取不同区域的 AmazonEC2 实例定价详细信息
【发布时间】:2020-03-27 14:45:23
【问题描述】:

使用 Aws 批量定价 API,我只能下载一个区域的 JSON,因此我正在寻找使用 Python 以编程方式获取所有区域的定价详细信息。

提前致谢。

【问题讨论】:

    标签: python-3.x amazon-web-services amazon-ec2 boto3


    【解决方案1】:

    就像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)
    

    【讨论】:

    • 我试过了,但它要求我提供凭据,我不会获取任何个人帐户详细信息,我只想获取不同地区所有 ec2 实例的定价详细信息
    • 好吧,你不能使用 boto 来做到这一点。但是你应该可以使用 python 请求来做到这一点。
    • 正如你所说,我可以使用请求来获取仅使用以下 URL pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/… 的一个区域(us-east-1)的详细信息,但无法下载其他区域的 JSON跨度>
    • @DhandapaniSudhakar 好的,我在没有 boto 的情况下使用正确的方法进行了编辑。
    • 非常感谢,我犯的错误是,我只是在 URL 中的两个地方替换了区域,现在我更改了它可以正常工作
    【解决方案2】:

    以下代码将下载不同地区的按需和预留期限实例定价详细信息并存储到我的本地系统中

    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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 2019-10-06
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2022-01-20
      • 2018-10-29
      • 1970-01-01
      相关资源
      最近更新 更多