Sub topic 12
Cross-checking prices with the AWS Price List API
This chapter assumes you can build a basic estimate in the AWS Pricing Calculator and read its monthly breakdown. It also assumes you have the AWS CLI configured and know what an AWS Region is. Basic Python helps for the second half.
Why cross-check at all
The calculator hides the arithmetic. It shows a monthly total for a line item, but it does not always show which unit rate sits behind it. If a number looks wrong, you need an independent source for the list price. The AWS Price List API is that source.
The API returns list prices: the public rates for a product before any discount, credit, or Free Tier allowance. Use it to check three things:
- The hourly or per-unit rate the calculator used for a configuration.
- Whether you picked the right attribute values, such as operating system, tenancy, or Region.
- Whether a hand calculation of the line item matches the calculator's figure.
It does not forecast usage, and it does not know about your account's negotiated pricing. It checks the price input, not the usage input.
The two Price List interfaces
AWS offers two ways to read prices. They carry the same underlying data.
| Interface | Shape | Best for |
|---|---|---|
| Price List Query API (`aws pricing`, `pricing` in boto3) | You filter by attributes and receive matching products | Looking up one configuration to verify a line item |
| Price List Bulk API | Large JSON or CSV offer files per service and Region, downloaded over HTTPS | Loading many prices into a spreadsheet or database |
This chapter uses the Query API because a cross-check usually concerns a handful of line items.
The Query API is served from a small set of endpoint Regions: us-east-1, ap-south-1, and eu-central-1 at the time of writing. The endpoint Region is not the Region whose prices you are reading. You can query us-east-1 for prices in Frankfurt. Which Region's price you get depends on the location filter.
How the lookup flows
Discovering what you can filter on
You do not have to guess attribute names. Two read-only calls list them.
aws pricing describe-services \
--region us-east-1 \
--service-code AmazonEC2 \
--max-items 1The response lists the attribute names available for that service, such as instanceType, location, operatingSystem, and tenancy. To see the valid values for one attribute:
aws pricing get-attribute-values \
--region us-east-1 \
--service-code AmazonEC2 \
--attribute-name operatingSystemUse the exact strings these calls return. The location attribute uses display names like US East (N. Virginia), not Region codes like us-east-1. This is the most common cause of an empty result.
Looking up one EC2 configuration
This query fetches the list-price product record for a t3.micro Linux instance in N. Virginia.
aws pricing get-products \
--region us-east-1 \
--service-code AmazonEC2 \
--filters \
"Type=TERM_MATCH,Field=instanceType,Value=t3.micro" \
"Type=TERM_MATCH,Field=location,Value=US East (N. Virginia)" \
"Type=TERM_MATCH,Field=operatingSystem,Value=Linux" \
"Type=TERM_MATCH,Field=tenancy,Value=Shared" \
"Type=TERM_MATCH,Field=preInstalledSw,Value=NA" \
"Type=TERM_MATCH,Field=capacitystatus,Value=Used" \
--max-items 1Each filter narrows the result. The last two are easy to forget. preInstalledSw=NA excludes images with preinstalled software such as SQL Server. capacitystatus=Used excludes the Capacity Reservation and Dedicated Host variants of the same instance type. Leave them out and you get several products that differ only in price.
Reading the response
PriceList is a list of strings, and each string is itself a JSON document. The CLI does not unwrap it for you. Each document has two parts you care about:
product.attributesdescribes what the price is for. Use it to confirm the product matches your line item.termsholds the prices. Underterms.OnDemand, each offer term containspriceDimensions, and each dimension hasunit(for EC2,Hrs) andpricePerUnit(a map such as{"USD": "..."}).
The rate is a string, not a number. Convert it before you do arithmetic.
Automating the check in Python
A script lets you check many line items and compare them with the calculator without copying values by hand. This one reuses the monthly formula from the earlier chapters.
import json
import boto3
HOURS_PER_MONTH = 730 # same basis the calculator uses for monthly estimates
pricing = boto3.client("pricing", region_name="us-east-1")
def on_demand_hourly_rate(instance_type, location="US East (N. Virginia)",
operating_system="Linux"):
"""Return the Linux/Shared On-Demand list price in USD per hour."""
attributes = {
"instanceType": instance_type,
"location": location,
"operatingSystem": operating_system,
"tenancy": "Shared",
"preInstalledSw": "NA",
"capacitystatus": "Used",
}
filters = [
{"Type": "TERM_MATCH", "Field": field, "Value": value}
for field, value in attributes.items()
]
response = pricing.get_products(
ServiceCode="AmazonEC2", Filters=filters, MaxResults=10
)
products = [json.loads(item) for item in response["PriceList"]]
if len(products) != 1:
raise ValueError(
f"Expected exactly 1 product, got {len(products)}. "
"Tighten the filters before trusting a rate."
)
for term in products[0]["terms"]["OnDemand"].values():
for dimension in term["priceDimensions"].values():
return float(dimension["pricePerUnit"]["USD"])
raise ValueError("No On-Demand price dimension found")
def monthly_compute_cost(hourly_rate, instance_count, utilization=1.0):
return hourly_rate * HOURS_PER_MONTH * utilization * instance_count
if __name__ == "__main__":
rate = on_demand_hourly_rate("t3.micro")
expected = monthly_compute_cost(rate, instance_count=3, utilization=0.5)
print(f"List rate: {rate} USD/hour")
print(f"Expected monthly cost for the line item: {expected:.2f} USD")The len(products) != 1 guard is deliberate. A query that returns zero or several products means your filters do not identify one price, and picking the first result would give a plausible but unverified number.
Run this under credentials that allow pricing:GetProducts, and optionally pricing:DescribeServices and pricing:GetAttributeValues. These calls read public price data and are not billed.
Interpreting a mismatch
Compute the expected monthly cost, then compare it with the calculator's line item. When the two differ, work through these causes in order. Most mismatches come from the first three.
- Different configuration. The calculator line item uses Windows, a different tenancy, or a different Region than your query. Compare
product.attributeswith the calculator's configuration. - Different usage basis. The calculator applies utilization or a "hours per month" setting that your script did not. Check that both use 730 hours, or the same fraction of it.
- Different pricing model. The calculator line item is a Savings Plan or Reserved Instance rate, while you read the
OnDemandterm. Reserved terms live underterms.Reservedand carry extra attributes such asLeaseContractLengthandPurchaseOption. - Free Tier or rounding. The calculator may subtract Free Tier usage, and it rounds displayed totals. A difference of a few cents can be rounding. A difference equal to a full allowance is the Free Tier.
- Price change. AWS updates prices over time. A saved estimate may reflect the rates at the time you built it, so rebuild or re-open it before assuming an error.
Beyond EC2
The same pattern works for other services. Change the service code and the filters:
- Use
describe-serviceswithout--service-codeto list service codes, such asAmazonEC2,AmazonS3, andAmazonRDS. - Use
get-attribute-valuesto find valid attribute values for the service you are checking. - Expect more than one price dimension for tiered services. S3 storage, for example, has tiers by volume, and each tier is a separate
priceDimensionsentry withbeginRangeandendRangevalues. Compare each tier against the calculator's tiered breakdown instead of reading one rate.
For data transfer, filter by transferType where the service exposes it, and remember the free allowances are not part of the list price record.
Limits of this technique
- It verifies unit rates. It cannot tell you whether 730 hours or 3 instances is the right usage.
- Attribute names differ per service, so each service needs a short exploration step before the script is reusable.
- Results can be large for loosely filtered queries. Use
MaxResultsor--max-itemsand tight filters, and followNextTokenwhen paging.
Exercise
Your calculator estimate shows 3 Linux instances running 50% of the month at a total that is about 2.5 times higher than your script's result. The script returned exactly one product. Name two likely causes and how you would check each.
Show answer
First, the calculator line item may use a different configuration than the script, such as Windows instead of Linux or Dedicated tenancy. Compare the calculator's options with the returned product.attributes. Second, the calculator may assume 100% utilization or a different hours basis. Check the utilization setting in the line item and confirm both calculations use 730 hours multiplied by the same fraction of the month. A third possibility is that the calculator used a Reserved or Savings Plan term while the script read the OnDemand term, which you would see by checking the pricing model on the line item.