Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
Table of Contents
GetUsageLinesEstimatedCost
ap-northeast-1
usageType
Whenever I manage cloud infrastructure migrations and scaling projects on AWS, one persistent challenge that always kept me up at night was the tedious friction of cost estimation—and the sudden shock of unexpected end-of-month cloud bills.
In modern engineering teams, developers provision resources effortlessly with Terraform or AWS CDK. More recently, autonomous AI agents like Claude Code, OpenCode, and Antigravity can spin up VPCs, NAT Gateways, EKS clusters, staging RDS databases, and bastion hosts within minutes from natural language prompts.
However, the dark side of this velocity is the risk of accidental over-provisioning and runaway costs. On one internal project, a developer provisioned a multi-AZ NAT Gateway setup for staging containers that routinely pulled multi-gigabyte container images and transferred high-volume logs. Within a single week, data transfer charges surged unexpectedly, triggering emergency billing alerts and frantic cleanup.
To eliminate such surprises, I repeatedly tried to establish automated FinOps guardrails in our CI/CD pipelines to calculate exactly how much a pull request (PR) would add to our monthly bill and block merging if budgets were exceeded. But until now, AWS lacked an out-of-the-box native solution:
pricing:GetProducts
“Why isn’t there a native, stateless AWS API that takes a list of planned usage lines and immediately returns an estimated total cost without persisting anything?”
On November 20, 2026, AWS answered that demand. AWS announced GetUsageLinesEstimatedCost , a powerful new API action in the Billing and Cost Management (BCM) Pricing Calculator.
▲ End-to-end architecture showing Terraform CI/CD and autonomous AI agents querying the AWS Pricing Calculator API statelessly to enforce pre-provisioning budget guardrails
The GetUsageLinesEstimatedCost API represents a fundamental shift in how AWS handles programmatic pricing calculations.
Its most critical capability is that it is completely stateless . It does not require saving, persisting, or managing the lifecycle of workloads or scenarios within an AWS account.
Previously, using the Pricing Calculator via APIs required creating a workload object, associating items with it, and later cleaning up obsolete estimates. GetUsageLinesEstimatedCost streamlines this into a pure request-response interaction.
usage
rateType
BEFORE_DISCOUNTS
AFTER_DISCOUNTS
AFTER_DISCOUNTS_AND_COMMITMENTS
key
[a-zA-Z0-9]*
lineItems
errors
estimatedCost
usageAmount
usageUnit
Hrs
GB-Mo
cost
currency
totalCost
By decoupling cost calculation from account-persisted state, teams can run fast, reliable, official cost calculations in CI/CD runners or local CLI environments in under half a second.
Let’s look at how I verified GetUsageLinesEstimatedCost on our remote testbed using the latest AWS CLI.
Ensure your AWS CLI v2 is updated to support bcm-pricing-calculator get-usage-lines-estimated-cost (v2.42.1+ recommended):
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
We will estimate a standard setup in Tokyo ( ap-northeast-1 ): one t3.medium EC2 instance (730 hours/month), 100 GB of gp3 EBS storage, and one active NAT Gateway (730 hours/month).
t3.medium
Create the request JSON payload ( usage-request.json ). Note that the top-level list key is "usage" (CLI flag --usage ) and each item’s "key" must satisfy [a-zA-Z0-9]* with a maximum length of 10 characters:
usage-request.json
"usage"
--usage
"key"
{ "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 } ] }
Execute the AWS CLI command:
$ aws bcm-pricing-calculator get-usage-lines-estimated-cost \ --cli-input-json file://usage-request.json \ --region us-east-1
Here is the raw response returned by the API:
{ "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": [] }
▲ Real-time terminal output on our remote testbed: instant calculation of $89.62/month across 3 usage lines via GetUsageLinesEstimatedCost
In approximately 0.4 seconds, the API returned precise calculations for Tokyo: $37.96 for the t3.medium instance (730 Hrs), $9.60 for the gp3 disk (100 GB-Mo), and $42.06 for the NAT Gateway hours (730 Hrs), totaling totalCost: 89.62 monthly.
totalCost: 89.62
Compared to manually building estimates in the console, the speed and automation readiness are remarkable.
While the API surface is straightforward, I encountered three distinct operational pitfalls when integrating this into automation scripts.
Two schema nuances frequently trip up first-time integrations:
First, each item’s key enforces min: 0, max: 10, pattern: [a-zA-Z0-9]* . Passing a raw Terraform resource address like aws_instance.web-server triggers a ValidationException due to hyphens, underscores, and length. Always map human-readable resource labels to short alphanumeric keys (e.g., item000001 ) in your wrapper script.
min: 0, max: 10, pattern: [a-zA-Z0-9]*
aws_instance.web-server
ValidationException
item000001
Second, in AWS billing, usage types for regional resources require a region abbreviation prefix, whereas US East (N. Virginia, us-east-1 ) often omits it. For instance, an EC2 instance in us-east-1 uses BoxUsage:t3.medium , but in Tokyo ( ap-northeast-1 ), it must be prefixed as APN1-BoxUsage:t3.medium .
us-east-1
BoxUsage:t3.medium
APN1-BoxUsage:t3.medium
If you provide an unrecognized usage type or invalid combination, the API still returns HTTP 200, but isolates the unpriceable item in the errors array ( errorCode : NOT_FOUND or 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." } ] }
Solution : Because unpriceable lines are excluded from totalCost ( “Usage lines returned in errors aren’t included” ), ignoring errors can silently under-report costs. Client scripts must always inspect errors and fail closed (block CI) if any unpriced resources exist.
bcm-pricing-calculator:
pricing:
When creating an IAM role for GitHub Actions or AI agent execution, it is tempting to use legacy pricing actions like Action: "pricing:Get*" . Doing so results in an AccessDeniedException .
Action: "pricing:Get*"
AccessDeniedException
The service namespace for this endpoint is bcm-pricing-calculator .
bcm-pricing-calculator
Configure least-privilege IAM permissions as follows:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowGetUsageLinesEstimatedCostOnly", "Effect": "Allow", "Action": [ "bcm-pricing-calculator:GetUsageLinesEstimatedCost" ], "Resource": "*" } ] }
Because this action is purely computational and does not inspect account resources or modify billing configurations, granting it to CI runners carries minimal risk.
For large infrastructure repositories where a single terraform plan modifies hundreds of resources across multiple modules, planned usage lines can easily exceed 500 items.
terraform plan
Exceeding the 500-item hard limit on usage triggers: ValidationException: 1 validation error detected: Value at 'usage' failed to satisfy constraint: Member must have length less than or equal to 500 .
ValidationException: 1 validation error detected: Value at 'usage' failed to satisfy constraint: Member must have length less than or equal to 500
Solution : Implement client-side chunking to split usage arrays into batches of 500 and aggregate totalCost , as demonstrated below.
Here is a production-grade Python script that accepts structured usage lines (e.g., extracted from Terraform JSON plan output), automatically normalizes labels into 10-character alphanumeric key identifiers, queries GetUsageLinesEstimatedCost , and evaluates budget guardrails:
#!/usr/bin/env python3 """ Real-time AWS Cost Estimation & FinOps Budget Guardrail Script Powered by AWS Pricing Calculator API (GetUsageLinesEstimatedCost) """ import sys import boto3 from botocore.exceptions import ClientError def chunk_list(items, chunk_size=500): """Yield successive chunks from items with a maximum size of 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"): """ Calls GetUsageLinesEstimatedCost with automatic 10-char alphanumeric key mapping and batching for >500 items. """ 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}" # Complies with [a-zA-Z0-9]* max 10 chars 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] Failed to query pricing calculator 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): """Enforces monthly budget thresholds and fails closed on unpriced errors.""" cost = estimation_result["totalCost"] errors = estimation_result["errors"] print("========================================") print(" FinOps Cost Estimation Report ") print("========================================") print(f"Applied Rate Type : {estimation_result['rateType']}") print(f"Total Estimated Cost: ${cost:.2f} USD / month") print(f"Budget Threshold : ${monthly_budget_threshold:.2f} USD / month") print(f"Line Items Priced : {len(estimation_result['lineItems'])}") for item in estimation_result["lineItems"]: est = item.get("estimatedCost", {}) print( f" - [{item['key']}] {item['originalLabel']} ({item['usageType']}): " f"{est.get('usageAmount')} {est.get('usageUnit')} => ${est.get('cost', 0.0):.2f} USD" ) if errors: print(f"\n[BLOCKED] 🚨 {len(errors)} unpriced line item errors occurred (Fail-Closed):") for err in errors: print( f" - [{err.get('key')}] {err.get('originalLabel')} | " f"Code: {err.get('errorCode')} | Msg: {err.get('errorMessage')}" ) return False print("----------------------------------------") if cost > monthly_budget_threshold: print(f"[BLOCKED] 🚨 Monthly estimate (${cost:.2f}) exceeds budget threshold (${monthly_budget_threshold:.2f})!") print("Provisioning blocked. Mandatory human review required.") return False else: print(f"[PASSED] ✅ Within budget. Provisioning may proceed.") return True if __name__ == "__main__": # Sample planned resources in Tokyo region 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") # Check against a $50/month threshold passed = enforce_finops_budget(result, monthly_budget_threshold=50.0) if not passed: sys.exit(1)
▲ Remote testbed verification: testing error isolation (NOT_FOUND / key regex validation) and blocking an over-budget workload ($95.12 > $50.00 threshold) via the Python FinOps Guardrail
Integrating this script into GitHub Actions allows teams to automatically block PR merges when proposed infrastructure exceeds target budget thresholds.
Beyond traditional CI/CD, the most transformative use case for GetUsageLinesEstimatedCost lies in safeguarding autonomous AI coding agents .
Today, developers routinely task autonomous agents (such as Antigravity, Claude Code, or OpenCode) with orchestrating cloud environments. An agent given a broad goal (“Create a resilient distributed queue processing worker pool”) will reliably write and attempt to deploy infrastructure.
However, LLMs inherently optimize for functional completeness rather than cost efficiency. Without strict boundaries, an agent might choose c6i.4xlarge instances instead of t4g.medium or provision provisioned IOPS SSDs ( io2 ) where standard gp3 suffices.
c6i.4xlarge
t4g.medium
io2
gp3
By equipping agents with an MCP (Model Context Protocol) tool that invokes GetUsageLinesEstimatedCost , we establish a self-regulating optimization loop:
As autonomous agents transition from drafting code to executing changes, native cost-estimation APIs provide the essential safety rails for responsible cloud automation.
The launch of AWS Pricing Calculator’s GetUsageLinesEstimatedCost on November 20, 2026, bridges a critical gap in automated cloud financial governance.
bcm-pricing-calculator:GetUsageLinesEstimatedCost
Because rateType supports BEFORE_DISCOUNTS , AFTER_DISCOUNTS , and AFTER_DISCOUNTS_AND_COMMITMENTS (depending on your account’s Pricing Calculator rate preferences, whereas billing transfer bill-source accounts are restricted to BEFORE_DISCOUNTS ), we will continue evaluating how commitment-adjusted rates behave across multi-account organizations in daily CI pipelines.
Integrate this API into your pipelines today to enforce proactive FinOps guardrails before cloud bills arrive.
Real-time AI quant analysis of earnings reports, corporate filings, and momentum indicators for global equities and Japanese stocks.
Master conversation skills with realistic AI phone training and 5-axis feedback. Includes 16-lesson interactive academy and studio AI portraits.
Effortlessly snap receipts for instant AI itemization. Integrated with LINE for seamless group expense tracking and pain-free settlement.
Interactive AI personas (Fortune Teller, Butler, Bartender) host real-time games, challenges, and conversation starters for unforgettable gatherings.
Unbiased healthcare database featuring zero-additive filters and active ingredient cost performance metrics.