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

AWS Lambda(Python)调用定价接口筛选EC2指定属性与价格问题

AWS EC2 Pricing接口返回结果过滤方案

实现思路

  • AWS Pricing get_products接口返回的PriceList字段中每个元素为JSON序列化字符串,需要先反序列化为字典才能提取字段
  • 实例的vcpu、内存、网络、操作系统等基础配置存储在product.attributes节点下
  • 实例价格存储在terms节点下,按需实例价格对应OnDemand子节点,预留实例价格对应Reserved子节点

完整修改后代码

import json
import boto3
client = boto3.client('pricing')
response1 = client.get_products(ServiceCode='AmazonEC2',
    Filters=[
        {
            'Field': 'instanceType', 'Type': 'TERM_MATCH', 'Value': 'r5.xlarge',
        },
        {
            'Field': 'operatingSystem', 'Type': 'TERM_MATCH', 'Value': 'Linux',
        },
        {
            'Field': 'vcpu','Type': 'TERM_MATCH', 'Value': '4',
        },
        {
            'Field': 'networkPerformance', 'Type': 'TERM_MATCH','Value': 'Up to 10 Gigabit',
        },
        {
            'Field': 'location','Type': 'TERM_MATCH', 'Value': 'EU (Paris)',
        },
        {
            'Field': 'usagetype', 'Type': 'TERM_MATCH', 'Value': 'EUW3-BoxUsage:r5.xlarge',
        },
    ],
    FormatVersion='aws_v1',
    MaxResults=100,
)

def lambda_handler(event, context):
    filtered_results = []
    # 遍历所有返回的价格条目
    for price_item_str in response1['PriceList']:
        # 反序列化JSON字符串为字典
        price_item = json.loads(price_item_str)
        attrs = price_item['product']['attributes']
        
        # 提取按需实例小时价格(默认取美元计价)
        price = "0"
        on_demand_terms = price_item['terms'].get('OnDemand', {})
        for term_val in on_demand_terms.values():
            for dim_val in term_val['priceDimensions'].values():
                price = dim_val['pricePerUnit'].get('USD', "0")
                break
            break
        
        # 组装指定字段
        filtered_item = {
            "vcpu": attrs.get("vcpu"),
            "Ram": attrs.get("memory"),
            "network": attrs.get("networkPerformance"),
            "os": attrs.get("operatingSystem"),
            "price_per_hour_usd": price
        }
        filtered_results.append(filtered_item)
    
    return {
        "statusCode": 200,
        "body": json.dumps(filtered_results, indent=2, ensure_ascii=False)
    }

补充说明

  • 如果需要提取其他币种的价格,替换pricePerUnit对应的USD为对应币种代码即可
  • 如果需要查询预留实例价格,增加terms.Reserved节点的提取逻辑即可
  • 现有过滤条件下返回的结果会自动去重,不会出现重复条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:54:01