You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boto3获取AWS按需实例每小时单价(Windows系统)

获取Amazon EC2按需共享租户非预留实例的每小时USD单价

我来帮你调整代码,精准拿到你需要的EC2实例价格信息~你的原代码缺少了几个关键过滤条件,咱们补上之后再加上价格解析的逻辑,就能直接输出每种实例类型对应的单价了。

完整代码实现

import boto3
import json

# 初始化Pricing客户端(注意:AWS Pricing API仅支持us-east-1区域)
client = boto3.client('pricing', region_name='us-east-1')

# 可以在这里批量定义要查询的实例类型,比如['m4.xlarge', 't3.medium']
target_instance_types = ['m4.xlarge']
operating_system = 'Windows'
target_region = 'US East (N. Virginia)'  # 也可以用区域代码,比如 'us-east-1'

for instance_type in target_instance_types:
    # 调用get_products,添加所有必要过滤条件
    response = client.get_products(
        ServiceCode='AmazonEC2',
        Filters=[
            {'Type': 'TERM_MATCH', 'Field': 'instanceType', 'Value': instance_type},
            {'Type': 'TERM_MATCH', 'Field': 'operatingSystem', 'Value': operating_system},
            {'Type': 'TERM_MATCH', 'Field': 'location', 'Value': target_region},
            {'Type': 'TERM_MATCH', 'Field': 'tenancy', 'Value': 'Shared'},  # 指定共享租户
            {'Type': 'TERM_MATCH', 'Field': 'termType', 'Value': 'OnDemand'},  # 指定按需实例
            {'Type': 'TERM_MATCH', 'Field': 'capacitystatus', 'Value': 'Used'},  # 筛选非预留实例
            {'Type': 'TERM_MATCH', 'Field': 'preInstalledSw', 'Value': 'NA'}  # 无预装软件,按需修改
        ]
    )

    # 解析响应数据,提取每小时USD单价
    for product in response['PriceList']:
        product_json = json.loads(product)
        # 定位按需定价的条款
        on_demand_terms = product_json['terms']['OnDemand']
        for term in on_demand_terms.values():
            price_dimensions = term['priceDimensions']
            for price_details in price_dimensions.values():
                hourly_price = price_details['pricePerUnit']['USD']
                print(f"✅ 实例类型: {instance_type}")
                print(f"💲 每小时单价 (USD): ${hourly_price}\n")

关键说明

  • 区域限制:AWS Pricing API只能在us-east-1区域调用,所以初始化客户端时必须指定这个区域
  • 过滤条件详解:
    • tenancy: Shared:确保返回的是共享租户的实例(对应专用租户的Dedicated)
    • termType: OnDemand:锁定按需计费类型,排除预留、竞价等其他计费方式
    • capacitystatus: Used:筛选非预留实例(预留实例的capacitystatus值为Reserved)
    • preInstalledSw: NA:如果你的实例需要预装SQL Server等软件,把这个值改成对应名称即可
  • 批量查询:如果需要查询多种实例类型,直接修改target_instance_types列表即可,代码会自动遍历输出每个类型的价格

内容的提问来源于stack exchange,提问作者jmoorhead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:50:40