使用Boto3调用AWS Pricing API无法获取RDS gp3/io2卷定价
问题描述
我已通过AWS Pricing API(Boto3)成功获取Amazon RDS中db.m6i.2xlarge实例的定价数据,但尝试以类似方式获取gp3、io2类型RDS卷的定价时,PriceList始终返回空值。
成功获取实例成本的代码:
def get_instance_cost_rds(region_name, instance_name, boto3_client): try: response = boto3_client.get_products( ServiceCode="AmazonRDS", Filters=[ {"Type": "TERM_MATCH", "Field": "instanceType", "Value": instance_name}, {"Type": "TERM_MATCH", "Field": "location", "Value": region_name}, {"Type": "TERM_MATCH", "Field": "databaseEngine", "Value": "PostgreSQL"} ], ) if response["PriceList"]: return response["PriceList"] except Exception as ex: logging.exception("Error fetching instance cost: %s", ex)
尝试获取gp3、io2卷定价的代码(返回空PriceList):
def get_volume_cost_rds(region_name, volume_type, boto3_client): try: response = boto3_client.get_products( ServiceCode="AmazonRDS", Filters=[ {"Type": "TERM_MATCH", "Field": "volumeType", "Value": volume_type}, {"Type": "TERM_MATCH", "Field": "location", "Value": region_name}, ], ) if response["PriceList"]: return response["PriceList"] else: print("No data found in PriceList for", volume_type) except Exception as ex: logging.exception("Error fetching volume cost: %s", ex) # Calling like this: region_name = "US East (N. Virginia)" boto3_client = boto3.client('pricing', region_name='us-east-1') gp3_prices = get_volume_cost_rds(region_name, "gp3", boto3_client) io2_prices = get_volume_cost_rds(region_name, "io2", boto3_client)
请问为何AWS Pricing API对RDS gp3/io2卷类型返回空PriceList?是否有特殊方式通过该API获取RDS卷定价?
解决方案
原因分析
RDS存储卷的定价条目在AWS Pricing API中需要更精确的过滤条件,你的代码缺少两个关键过滤项:
productFamily过滤:RDS存储属于Database Storage产品族,不指定的话,API会返回所有RDS相关产品(实例、备份、存储等),但无法精准匹配到存储卷条目。databaseEngine过滤:虽然RDS存储定价通常跨引擎一致,但API的TERM_MATCH逻辑需要明确指定数据库引擎才能返回有效结果,否则可能因为匹配范围过宽导致无数据。
修正后的代码
修改get_volume_cost_rds函数,补充上述两个过滤条件:
def get_volume_cost_rds(region_name, volume_type, engine_name, boto3_client): try: response = boto3_client.get_products( ServiceCode="AmazonRDS", Filters=[ {"Type": "TERM_MATCH", "Field": "volumeType", "Value": volume_type}, {"Type": "TERM_MATCH", "Field": "location", "Value": region_name}, {"Type": "TERM_MATCH", "Field": "productFamily", "Value": "Database Storage"}, {"Type": "TERM_MATCH", "Field": "databaseEngine", "Value": engine_name} ], ) if response["PriceList"]: return response["PriceList"] else: print("No data found in PriceList for", volume_type) except Exception as ex: logging.exception("Error fetching volume cost: %s", ex) # 调用示例(和实例使用相同的引擎) region_name = "US East (N. Virginia)" boto3_client = boto3.client('pricing', region_name='us-east-1') gp3_prices = get_volume_cost_rds(region_name, "gp3", "PostgreSQL", boto3_client) io2_prices = get_volume_cost_rds(region_name, "io2", "PostgreSQL", boto3_client)
额外说明
- 如果需要获取通用的RDS存储定价(不区分引擎),可以尝试将
databaseEngine的Value设为"Any",但部分区域可能不支持该取值,建议优先使用具体引擎名称。 - 对于io2卷,还可以根据需求添加
storageMedia过滤(比如"SSD"),但不是必须项,视返回结果调整。
内容的提问来源于stack exchange,提问作者Aparna
相关产品推荐
相关产品推荐

