Kanji
・云架构工程师 / 自由职业 ・1993年出生 ・爱媛县出身 / 现居东京都涩谷区 ・5年 AWS 实战经验 个人资料详情
目录
ap-northeast-1
usageType
key
在推进企业云迁移和 AWS 基础设施建设的过程中,最让我头疼的莫过于“部署前成本测算的繁琐流程,以及月底看到账单那一刻的惊吓”。
如今开发人员可以轻松地用 Terraform 或 AWS CDK 拉起资源;甚至只需用自然语言向自主 AI 编程智能体(如 Antigravity、Claude Code、OpenCode 等)下达一句“帮我搭建一套测试用的预发环境”,短短几分钟内,VPC、NAT Gateway、EKS 集群、测试 RDS 和跳板机 EC2 就会被自动编排完成。
但这种高效率背后的隐患,就是“无意间拉起过高规格或昂贵计费的资源”。 在之前的一个内部测试项目中,开发人员在多可用区(Multi-AZ)冗余部署了 NAT Gateway,测试容器频繁拉取数 GB 的镜像并传输海量日志,结果短短一周内数据传输与网关小时费就飙升了数百美元,直到月底触发账单告警才紧急清理。
为了防止此类事故,我曾多次尝试在 Pull Request(PR)阶段自动计算“本次基础设施变更将增加多少月度费用”,并在超出预算时自动拦截 CI 的 FinOps 护栏。但长期以来,AWS 原生工具链存在明显短板:
pricing:GetProducts
“如果 AWS 能提供一个官方原生的无状态(Stateless)API,只需把规划的用量明细发过去,就能当场返回汇总估算金额该多好……”
2026 年 11 月 20 日,AWS 终于回应了云架构师们的期盼,在 AWS Billing and Cost Management (BCM) Pricing Calculator 中正式推出了全新 API: GetUsageLinesEstimatedCost 。
GetUsageLinesEstimatedCost
▲ 整体架构:Terraform CI/CD 与自主 AI 智能体通过 AWS Pricing Calculator API 进行无状态实时成本推估并执行预算护栏
新发布的 GetUsageLinesEstimatedCost 彻底改变了以往使用 AWS Pricing Calculator 的方式。
它最核心的特性是 “完全无状态(Stateless)——完全不需要在 AWS 账户中持久化或保存任何估算对象(Workload 或 Scenario)” 。
过去若想通过 API 操作 Pricing Calculator,必须先创建并保存一个 Workload 对象,将资源绑定上去,事后还要清理废弃的估算记录。而 GetUsageLinesEstimatedCost 采用纯粹的请求-响应模式,即查即走。
usage
rateType
BEFORE_DISCOUNTS
AFTER_DISCOUNTS
AFTER_DISCOUNTS_AND_COMMITMENTS
[a-zA-Z0-9]*
lineItems
errors
Hrs
GB-Mo
estimatedCost
totalCost
下面展示我在远程测试环境中,使用最新 AWS CLI v2 调用 GetUsageLinesEstimatedCost 的完整过程与真实响应日志。
调用该 API 需要支持 bcm-pricing-calculator get-usage-lines-estimated-cost 的新版 AWS CLI v2(建议 v2.42.1 及以上)或最新 Boto3 SDK。
bcm-pricing-calculator get-usage-lines-estimated-cost
$ aws --version aws-cli/2.42.1 Python/3.13.9 Darwin/25.6.0 exe/arm64
我们来测算一套东京区域( ap-northeast-1 )常见的开发基准环境:1 台 t3.medium 实例(730 小时/月)、100 GB gp3 云盘,以及 1 个 NAT Gateway(730 小时/月)。
t3.medium
gp3
创建请求 JSON 文件( usage-request.json )。注意顶层数组字段名为 "usage" (CLI 参数为 --usage ),且 key 必须为 10 字符以内的纯字母数字(不可包含连字符 - ) :
usage-request.json
"usage"
--usage
-
{ "rateType": "BEFORE_DISCOUNTS", "usage": [ { "key": "webEc201", "serviceCode": "AmazonEC2", "usageType": "APN1-BoxUsage:t3.medium", "operation": "RunInstances", "amount": 730.0 }, { "key": "webEbs01", "serviceCode": "AmazonEC2", "usageType": "APN1-EBS:VolumeUsage.gp3", "operation": "CreateVolume", "amount": 100.0 }, { "key": "natGw01", "serviceCode": "AmazonEC2", "usageType": "APN1-NatGateway-Hours", "operation": "CreateNatGateway", "amount": 730.0 } ] }
执行 AWS CLI 命令:
$ aws bcm-pricing-calculator get-usage-lines-estimated-cost \ --cli-input-json file://usage-request.json \ --region us-east-1
API 返回的原始 JSON 响应如下:
{ "rateType": "BEFORE_DISCOUNTS", "totalCost": 89.62, "currency": "USD", "lineItems": [ { "key": "webEc201", "serviceCode": "AmazonEC2", "usageType": "APN1-BoxUsage:t3.medium", "operation": "RunInstances", "estimatedCost": { "usageAmount": 730.0, "usageUnit": "Hrs", "cost": 37.96, "currency": "USD" } }, { "key": "webEbs01", "serviceCode": "AmazonEC2", "usageType": "APN1-EBS:VolumeUsage.gp3", "operation": "CreateVolume", "estimatedCost": { "usageAmount": 100.0, "usageUnit": "GB-Mo", "cost": 9.60, "currency": "USD" } }, { "key": "natGw01", "serviceCode": "AmazonEC2", "usageType": "APN1-NatGateway-Hours", "operation": "CreateNatGateway", "estimatedCost": { "usageAmount": 730.0, "usageUnit": "Hrs", "cost": 42.06, "currency": "USD" } } ], "errors": [] }
▲ 远程测试环境实机终端截图:单次调用 GetUsageLinesEstimatedCost 在 384ms 内算出 3 项明细共计 $89.62/月
耗时仅约 0.4 秒,东京区域的 t3.medium (730 Hrs = $37.96)、 gp3 100GB(100 GB-Mo = $9.60)和 NAT Gateway(730 Hrs = $42.06)以及总费用 totalCost: 89.62 USD 就精准返回了。
totalCost: 89.62
在将该 API 集成到自动化脚本的过程中,我踩过三个非常典型的坑,分享出来供大家避坑。
首先是 key 字段的校验规则: min: 0, max: 10, pattern: [a-zA-Z0-9]* (仅限字母和数字,最长 10 个字符) 。如果直接把 Terraform 资源地址(如 aws_instance.web-server )传给 key ,会因为包含下划线、连字符以及超出 10 字符而直接抛出 ValidationException 。因此在封装脚本中,必须将可读标签映射为短编号(如 item000001 )。
min: 0, max: 10, pattern: [a-zA-Z0-9]*
aws_instance.web-server
ValidationException
item000001
其次是 usageType 的区域缩写前缀。在 AWS 计费体系中,美东(弗吉尼亚北部 us-east-1 )通常不带前缀(直接写 BoxUsage:t3.medium ),而东京区域( ap-northeast-1 )则必须加上 APN1- 前缀(即 APN1-BoxUsage:t3.medium )。
us-east-1
BoxUsage:t3.medium
APN1-
APN1-BoxUsage:t3.medium
如果传入了不匹配的 usageType ,API 依然返回 HTTP 200,但会将无法计价的明细隔离到 errors 数组中( errorCode 为 NOT_FOUND 或 BAD_REQUEST ):
errorCode
NOT_FOUND
BAD_REQUEST
{ "rateType": "BEFORE_DISCOUNTS", "totalCost": 0.0, "currency": "USD", "lineItems": [], "errors": [ { "key": "webEc201", "serviceCode": "AmazonEC2", "usageType": "APN1-InvalidBox:t3.medium", "operation": "RunInstances", "errorCode": "NOT_FOUND", "errorMessage": "No matching price found for serviceCode AmazonEC2, usageType APN1-InvalidBox:t3.medium, operation RunInstances." } ] }
解决方案 : 官方文档明确指出 errors 中的明细不会计入 totalCost 。如果忽略 errors 数组,会导致总成本被严重低估。因此客户端脚本必须严格检查 errors ,只要存在任何一条错误,就必须按 Fail-Closed 原则阻断流水线。
bcm-pricing-calculator:
pricing:
为 CI/CD 角色或 AI 智能体配置 IAM 权限时,切勿习惯性地写成 pricing:Get* ,否则会报 AccessDeniedException 。
pricing:Get*
AccessDeniedException
最小权限 IAM 策略配置如下:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowGetUsageLinesEstimatedCostOnly", "Effect": "Allow", "Action": [ "bcm-pricing-calculator:GetUsageLinesEstimatedCost" ], "Resource": "*" } ] }
对于管理数百个资源的大型 Terraform 仓库,单次变更可能超过 500 条明细。超出上限会触发 ValidationException 。在客户端按 500 条为单位进行切片(Chunking)并累加 totalCost 即可完美解决。
下面是可直接用于生产流水线的 Python 脚本,内置了 10 字符 key 自动映射、500 条分块请求以及 Fail-Closed 预算阈值校验:
#!/usr/bin/env python3 """ 基于 AWS Pricing Calculator API (GetUsageLinesEstimatedCost) 的 实时部署前成本推估与 FinOps 预算护栏脚本 """ import sys import boto3 from botocore.exceptions import ClientError def chunk_list(items, chunk_size=500): """将列表按最大 500 条分块""" for i in range(0, len(items), chunk_size): yield items[i : i + chunk_size] def estimate_workload_costs(usage_lines, rate_type="BEFORE_DISCOUNTS", region_name="us-east-1"): """调用 GetUsageLinesEstimatedCost,支持 10 字符 key 自动映射与 500 条分块累加""" client = boto3.client("bcm-pricing-calculator", region_name=region_name) total_cost = 0.0 all_line_items = [] all_errors = [] for chunk_idx, chunk in enumerate(chunk_list(usage_lines, 500)): key_map = {} api_usage_payload = [] for idx, item in enumerate(chunk): short_key = f"item{chunk_idx:02d}{idx:04d}" key_map[short_key] = item.get("label", short_key) api_usage_payload.append({ "key": short_key, "serviceCode": item["serviceCode"], "usageType": item["usageType"], "operation": item["operation"], "amount": float(item["amount"]), }) try: response = client.get_usage_lines_estimated_cost( rateType=rate_type, usage=api_usage_payload, ) total_cost += response.get("totalCost", 0.0) for priced in response.get("lineItems", []): priced["originalLabel"] = key_map.get(priced["key"], priced["key"]) all_line_items.append(priced) for err in response.get("errors", []): err["originalLabel"] = key_map.get(err["key"], err["key"]) all_errors.append(err) except ClientError as e: print(f"[ERROR] API 调用失败: {e}", file=sys.stderr) raise e return { "rateType": rate_type, "totalCost": round(total_cost, 2), "currency": "USD", "lineItems": all_line_items, "errors": all_errors, } def enforce_finops_budget(estimation_result, monthly_budget_threshold=100.0): """执行预算阈值校验,存在未算出错误或超预算时 Fail-Closed 阻断""" cost = estimation_result["totalCost"] errors = estimation_result["errors"] print("========================================") print(" FinOps 部署前成本推估报告 ") print("========================================") print(f"应用费率类型 : {estimation_result['rateType']}") print(f"预估月度总成本 : ${cost:.2f} USD") print(f"月度预算上限 : ${monthly_budget_threshold:.2f} USD") print(f"成功计价明细数 : {len(estimation_result['lineItems'])} 条") if errors: print(f"\n[BLOCKED] 🚨 存在 {len(errors)} 条未成功计价错误(Fail-Closed 阻断)") return False if cost > monthly_budget_threshold: print(f"[BLOCKED] 🚨 超出月度预算上限 (${monthly_budget_threshold:.2f})!需人工审批。") return False else: print(f"[PASSED] ✅ 符合预算,允许继续部署。") return True if __name__ == "__main__": sample_usage = [ { "label": "prod-app-server-t3-large", "serviceCode": "AmazonEC2", "usageType": "APN1-BoxUsage:t3.large", "operation": "RunInstances", "amount": 730.0, }, { "label": "prod-app-db-gp3", "serviceCode": "AmazonEC2", "usageType": "APN1-EBS:VolumeUsage.gp3", "operation": "CreateVolume", "amount": 200.0, }, ] result = estimate_workload_costs(sample_usage, rate_type="BEFORE_DISCOUNTS") if not enforce_finops_budget(result, monthly_budget_threshold=50.0): sys.exit(1)
▲ 远程验证环境实测:错误隔离验证(NOT_FOUND)、CloudTrail 审计追踪与 Python FinOps 护栏拦截超预算变更($95.12 > $50.00)
除了传统 CI/CD,这项 API 最具变革意义的场景是作为 “自主 AI 编程智能体(Autonomous Coding Agents)的财务安全网” 。
大模型擅长满足功能需求,但往往对云成本不敏感(例如随意选用 c6i.4xlarge 或高价 io2 卷)。将 GetUsageLinesEstimatedCost 封装为 MCP 工具交给智能体后,智能体可以在执行 terraform apply 前自我测算成本;若超预算则自动切换为 Graviton 实例或 gp3 存储,只有在无法进一步优化时才升级请求人工审批。
c6i.4xlarge
io2
terraform apply
bcm-pricing-calculator:GetUsageLinesEstimatedCost
Real-time AI quant analysis of corporate earnings reports.
提供逼真 AI 模拟通话与多维反馈,结合 16 讲实战社交学院与工作室级 AI 肖像生成,全面提升社交互动质量。
拍小票即可完成高精度智能拆单,支持 LINE 登录无缝结算团队聚会支出,告别繁琐账单分摊。
占卜师、管家、调酒师等 AI 角色实时引导话题与聚会游戏,让线下与线上聚餐氛围瞬间升温。
人工甘味料や添加物のNG除外と有効成分あたりの実質単価比較データベース。