Sub topic 13
Running cost queries from the AWS CLI
This chapter shows how to run the Cost Explorer queries from earlier chapters with the aws ce commands. It assumes you can already group and filter in the console, that cost allocation tags are activated for your account, and that the AWS CLI v2 is installed with credentials configured. Each section maps a console control to a command option.
What the CLI calls
aws ce is a front end to the Cost Explorer API. It returns the same data as the console, as JSON that scripts can process. The commands you will use most:
| Command | Purpose |
|---|---|
| `get-cost-and-usage` | Historical cost or usage, with grouping and filtering |
| `get-dimension-values` | Valid values for a dimension such as `SERVICE` or `LINKED_ACCOUNT` |
| `get-tags` | Tag keys and values seen in a period |
| `get-cost-forecast` | Projected spend for a future period |
| `list-cost-allocation-tags` | Which tag keys are active |
Your first query
This returns October 2026 cost per service:
aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=DIMENSION,Key=SERVICEThree details cause most first-time mistakes:
Endis exclusive. To cover all of October, useEnd=2026-11-01, not2026-10-31.- Dates are
YYYY-MM-DD. WithHOURLYgranularity you useYYYY-MM-DDThh:mm:ssZinstead. Hourly data must be enabled in Cost Explorer settings and covers only a recent window. - The response is a list of time buckets. Each element of
ResultsByTimehas aTimePeriod, aTotal(empty when you group) and aGroupslist. Each group hasKeysandMetrics.
A trimmed response looks like this:
{
"ResultsByTime": [
{
"TimePeriod": { "Start": "2026-10-01", "End": "2026-11-01" },
"Total": {},
"Groups": [
{
"Keys": ["Amazon Elastic Compute Cloud - Compute"],
"Metrics": { "UnblendedCost": { "Amount": "1843.2190000000", "Unit": "USD" } }
}
],
"Estimated": false
}
]
}Amount is a string, not a number. Convert it before arithmetic. Estimated is true for periods that are not yet final, which usually means the current month.
Choosing metrics
Pass one or more values to --metrics. The ones that matter for this tutorial:
UnblendedCost: the cost as charged on the day of use.AmortizedCost: spreads upfront Reserved Instance and Savings Plans fees across the term.NetUnblendedCostandNetAmortizedCost: the same measures after discounts are applied.UsageQuantity: units used, such as GB-months or instance hours.
You can request several metrics in one call, for example --metrics UnblendedCost AmortizedCost. UsageQuantity only makes sense when you group by USAGE_TYPE or filter to a single usage type, because summing unlike units is meaningless.
Grouping by tag and by dimension
--group-by accepts up to two groupings. Each has a Type of DIMENSION, TAG or COST_CATEGORY, and a Key. This groups October cost by the Project tag:
aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=TAG,Key=ProjectTag group keys come back as Key$Value, for example Project$checkout. Spend with no Project tag appears as Project$, with nothing after the dollar sign. That entry is your untagged spend.
Two groupings give a matrix. This returns service within project:
aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=TAG,Key=Project Type=DIMENSION,Key=SERVICEEach group's Keys array then has two entries, in the order you listed the groupings.
Filtering with a JSON expression
Filters are nested expressions, which are awkward on the command line. Save them to a file and pass file://. This filter limits a query to EC2 compute spend tagged Environment=prod:
{
"And": [
{ "Dimensions": { "Key": "SERVICE", "Values": ["Amazon Elastic Compute Cloud - Compute"] } },
{ "Tags": { "Key": "Environment", "Values": ["prod"] } }
]
}aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity DAILY \
--metrics UnblendedCost \
--filter file://filter.jsonThe expression has three combinators, And, Or and Not. Each leaf is Dimensions, Tags or CostCategories. Rules to remember:
AndandOrtake a list. Each list element must hold exactly one leaf or one combinator.- Service names must match exactly. Look them up with
aws ce get-dimension-values --time-period Start=2026-10-01,End=2026-11-01 --dimension SERVICEinstead of guessing. - Tag values are case-sensitive by default, so
Prodandprodare different values.
To find only resources missing a tag, use the ABSENT match option:
{
"Tags": { "Key": "Project", "MatchOptions": ["ABSENT"] }
}Running a query with this filter, grouped by SERVICE, tells you which services produce your untagged spend. That is a more direct view than reading the Project$ group.
Shaping output with --query
The CLI's built-in --query option takes a JMESPath expression, so you can often skip jq. This prints one line per project, with its cost:
aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=TAG,Key=Project \
--query 'ResultsByTime[].Groups[].[Keys[0], Metrics.UnblendedCost.Amount]' \
--output textWith --granularity DAILY or MONTHLY over several months, ResultsByTime has several elements. The expression above flattens them, so you lose which period each row belongs to. Include TimePeriod.Start if that matters, and keep the nesting in mind when you write the expression.
Large results and forecasts
When a result is too large, the response includes a NextPageToken. Pass it back with --next-page-token and the same other options to get the next page. Grouping by USAGE_TYPE or by a tag with many values is the usual cause. Every page is a billed request, so narrow the filter first.
To ask what the month will cost, use the forecast call. The start must be today or later, and the end is exclusive:
aws ce get-cost-forecast \
--time-period Start=2026-11-27,End=2026-12-01 \
--metric UNBLENDED_COST \
--granularity MONTHLYNote that the forecast takes --metric (singular, with an underscore style such as UNBLENDED_COST), unlike --metrics UnblendedCost in the history call. Forecasts need enough history to work, and a new account may get an error.
Common errors
| Error | Likely cause |
|---|---|
| `DataUnavailableException` | The date range is outside the retained history, or the account has no Cost Explorer data yet |
| `BillExpirationException` | The requested period is too old for the API |
| `AccessDeniedException` | The IAM identity lacks the matching `ce:` permission, or member-account access to Cost Explorer is turned off |
| `ValidationException` on dates | `End` is before `Start`, or the format is wrong |
| Everything under `Project$` | The tag is not activated, or the usage predates activation |
| Totals differ from the console | Different metric, or the console view uses a different grouping or filter |
Each action maps to an IAM permission of the same name, such as ce:GetCostAndUsage and ce:GetTags. Activating tags needs ce:UpdateCostAllocationTagsStatus, which is separate from the read permissions.
Putting it together
A small script that reports what share of last month's spend is untagged needs only two calls, one with no grouping and one with the ABSENT filter:
#!/usr/bin/env bash
set -euo pipefail
START=2026-10-01
END=2026-11-01
echo '{"Tags":{"Key":"Project","MatchOptions":["ABSENT"]}}' > /tmp/untagged.json
total=$(aws ce get-cost-and-usage \
--time-period Start=$START,End=$END \
--granularity MONTHLY --metrics UnblendedCost \
--query 'ResultsByTime[0].Total.UnblendedCost.Amount' --output text)
untagged=$(aws ce get-cost-and-usage \
--time-period Start=$START,End=$END \
--granularity MONTHLY --metrics UnblendedCost \
--filter file:///tmp/untagged.json \
--query 'ResultsByTime[0].Total.UnblendedCost.Amount' --output text)
awk -v t="$total" -v u="$untagged" \
'BEGIN { printf "Untagged: %.2f of %.2f USD (%.1f%%)\n", u, t, 100*u/t }'This works because an ungrouped query fills Total, and MONTHLY over one calendar month yields a single element in ResultsByTime.
Exercise
You run a query grouped by Type=TAG,Key=Team for October 2026 and nearly all cost appears in the group Team$. Name two possible causes, and give one CLI command that checks the first and one query option that shows which services contribute to the Team$ group.
Show answer
Possible causes: the Team tag key is not activated as a cost allocation tag (or was activated after the usage occurred), or the resources really do not carry the tag. Check activation with aws ce list-cost-allocation-tags --status Active. To see which services produce the untagged spend, filter with {"Tags":{"Key":"Team","MatchOptions":["ABSENT"]}} through --filter file://... and add --group-by Type=DIMENSION,Key=SERVICE.