Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

azure-cost-cli

> 开发工具
Open source

CLI tool to perform cost analysis on your Azure subscription

1.1K stars0 likes1 views
WebsiteGitHub

About

CLI tool to perform cost analysis on your Azure subscription

Azure Cost CLI

This is a simple command line tool to get the cost of your Azure subscription. It uses the Azure Cost Management API to get the cost and output the results to the console, text, csv, markdown or JSON. E.g. so it can be used in a workflow to get the cost of your subscription and use it in subsequent steps.

⚠️ Important: This tool uses the Azure Cost Management API. Not all Azure subscription types are supported by this API (e.g., sponsored subscriptions). Please check if your subscription is compatible before using this tool.

Besides showing the accumulated cost, it can also show daily cost, extract resource (costs) and list budgets.

It can also detect anomalies and trends in the cost, which can be used to further automate reporting.

Installation

Prerequisites

  • .NET 8.0 or .NET 10.0 runtime
  • Azure CLI authenticated (az login) or an Azure identity with Cost Management Reader role

You can install this tool globally, using the dotnet tool command:

bash
dotnet tool install --global azure-cost-cli 

Upgrading

When there is a new version available on NuGet, you can use the dotnet tool update command to upgrade:

bash
dotnet tool update --global azure-cost-cli 

With a --version parameter, you can specify a specific version to install. Use the --no-cache parameter to force a re-download of the package if it cannot find the latest version.

Usage

You can invoke the tool using the azure-cost command. You can use the --help parameter to get a list of all available options. Some of the commands have additional parameters which can be shown by adding the specific command with the --help option.

bash
azure-cost --help

Which will show:

…

Starting from version 0.35, you can select a different scope besides only subscription. Specify subscription id and resourcegroup name, billing account and/or enrollment account to scope the request to that level.

When you do not specify a subscription id, it will fetch the actively selected one of the az cli instead.

If the application is not working properly, you can use the --debug parameter to increase the logging verbosity and see more details.

This tool uses the Azure Cost Management API to get the cost. Not all subscriptions have access to this API. To check if your subscription has access, you can use the az account subscription show --subscription-id yourid --query '[subscriptionPolicies.quotaId]' -o tsv command. Validate the resulting quota id with the ones on the Microsoft list to see if it is supported. Running the tool with the --debug parameter will also show the quota id that is used.

There is a pretty strict rate limit on the cost api; the calls are retried after a 429 is received, but it might take a while before the call succeeds as it honors the retry time out.

Authentication

To make the call to the Azure cost API, you do need to run this from a user account with permissions to access the cost overview of the subscription. Further more, it needs to find the active credentials and it does so by using the ChainedTokenCredential provider which will look for the az cli token first. Make sure to run az login (with optionally the --tenant parameter) to make sure you have an active session.

Configuration file

You can persist default settings in a JSON config file so you don't have to repeat common flags on every command.

File locations (evaluated in order, later values override earlier ones):

Path Purpose
~/.azure-cost-cli.json Global user defaults
.azure-cost-cli.json (current directory) Project-level defaults, override global
Path in AZURE_COST_CLI_CONFIG env var Overrides both of the above entirely

Supported keys:

json
{
  "subscription": "00000000-0000-0000-0000-000000000000",
  "output": "Json",
  "timeframe": "BillingMonthToDate",
  "useUSD": false,
  "metric": "ActualCost",
  "othersCutoff": 10
}

All keys are optional. CLI flags always take precedence over config file values — the config only supplies defaults.

Example: Set a default subscription and output format globally so you never have to pass -s or -o:

bash
cat > ~/.azure-cost-cli.json  report.txt

# Use in a script without spinner noise cluttering stderr
azure-cost dailyCosts -o json --quiet | jq '.[] | .cost'

You can use this tool in a GitHub workflow to get the cost of your subscription and store the results in markdown as a Job Summary. This can be used to get a quick overview of the cost of your subscription. Have a look at the workflow in this repository for an example output.

…

The last step outputs the markdown to the Job Summary. This can be used to show the cost of the subscription in the workflow summary. Use it on a schedule to get for example a daily overview. Alternatively you can use the -o json parameter to get the results in JSON format and use it for further processing.

CI/CD Cost Gates

Use the --fail-if-over flag to fail a pipeline step when costs exceed a threshold. When the total cost exceeds the specified amount, the command writes a warning to stderr and exits with code 1. Output is still written normally before the check, so piped output (e.g. to a file) is not affected.

Supported commands: accumulatedCost, costByResource, dailyCosts.

Example: GitHub Actions cost gate

yaml
- name: Check Azure costs
  run: azure-cost accumulatedCost -s ${{ secrets.AZURE_SUBSCRIPTION_ID }} -o json --fail-if-over 500 > costs.json

If costs exceed 500, the step fails and the workflow stops (or you can use continue-on-error: true to proceed with a warning). The JSON output is still written to costs.json regardless.

Available commands

Accumulated Cost

This will retrieve the accumulated cost of the subscription. This is the total cost of the subscription since the beginning of the period specified. We will try to fetch the forecast as well and organise by location, type and resource group. You can use the different formatters to get the results in different formats.

bash
azure-cost accumulatedCost -s 574385a9-08e9-49fe-91a2-27660d92b8f5

This is the default command when you do not specify a command.

Cost By Resource

This will retrieve the cost of the subscription by resource. This will fetch the resource details including the meter information. It is up to the formatter how this is returned. Use the json formatter to get the full details.

bash
azure-cost costByResource -s 574385a9-08e9-49fe-91a2-27660d92b8f5 -o json

If you are only interested in the cost of the resources, you can exclude the meter details using the --exclude-meter-details parameter.

bash
azure-cost costByResource -s 574385a9-08e9-49fe-91a2-27660d92b8f5 --exclude-meter-details

Do keep in mind that with the --metric you can either request the ActualCost or the AmortizedCost cost, but not both at the same time. The default is ActualCost.

A resource can be in multiple resource locations, like Intercontinental and West Europe. When you use --exclude-meter-details, the resource will be listed once and the locations will be combined.

You can parse out the resource name, group name and subscription id from the ResourceId field. The format is /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.

Sorting and limiting results

Use --sort to control the order of resources. The default is cost (descending, most expensive first). Available options: cost, cost-asc, name, resource-group, resource-type, location.

bash
azure-cost costByResource -s 574385a9-08e9-49fe-91a2-27660d92b8f5 --sort name

Use --top N to show only the top N resources. Use 0 to show all (the default).

bash
azure-cost costByResource -s 574385a9-08e9-49fe-91a2-27660d92b8f5 --top 10

Combine both to get, for example, the 5 most expensive resources:

bash
azure-cost costByResource -s 574385a9-08e9-49fe-91a2-27660d92b8f5 --top 5 --sort cost

Note: --top limits the total number of resources passed to formatters. This is different from --others-cutoff, which collapses smaller items into an "Others" row in console output.

Cost By Tag

This will retrieve the cost of the subscription by the provided tag key(s). So if you tag your resources with, e.g. a cost-center or a creator, you can retrieve the cost of the subscription by those tags. You can specify multiple tags by using the --tag parameter multiple times.

bash
azure-cost costByTag  --tag cost-center --tag creator

By default, resources without the specified tag(s) are included in an (untagged) group, making it easy to see what percentage of spend is properly tagged. To exclude untagged resources (the old behavior), use --include-untagged false:

bash
azure-cost costByTag --tag cost-center --include-untagged false

The csv, json(c) and console output will render the results, either hierarchically or flattened in the case of the csv export.

If you require more formatters, let me know!

Daily Costs

The daily overview fetches the cost of the subscription for each day in the specified period. It will show the total cost of the day and the cost per dimension. The dimension is the resource group by default, but you can specify a different one using the --dimension parameter.

For example:

bash
azure-cost dailyCosts -s 574385a9-08e9-49fe-91a2-27660d92b8f5 --dimension ResourceLocation

The default dimension is the resource group.

bash
azure-cost dailyCosts 

The above screenshots show the default console output, but the other formatters can also be used.

The available dimensions are: ResourceGroup,ResourceGroupName,ResourceLocation,ConsumedService,ResourceType,ResourceId,MeterId,BillingMonth,MeterCategory,MeterSubcategory,Meter,AccountName,DepartmentName,SubscriptionId,SubscriptionName,ServiceName,ServiceTier,EnrollmentAccountName,BillingAccountId,ResourceGuid,BillingPeriod,InvoiceNumber,ChargeType,PublisherType,ReservationId,ReservationName,Frequency,PartNumber,CostAllocationRuleName,MarkupRuleName,PricingModel,BenefitId,BenefitName

Include Tags

This option allows to include the dimensions' Tags in the same row. Tags allow cost analysis customization. Adding the Tags from the dimension allows complementary analysis in tools like Power BI. This option is enabled for DailyCost report and for Json, JsonC, and Csv expor formats. Using other formats, ignores the option.

The following query shows the daily costs for subscription x group by resource group name including the tags for the resource group ready to export to Csv:

bash
azure-cost dailyCosts -s XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX --dimension ResourceGroupName --includeTags -o Csv

That would extend into a column called Tags the resource group tags in Json format:

bash
[""\""cost-center\"":\""my_cost_center\"""",""\""owner\"":\""[email protected]\""""]

Note that the Json column should be parsed in the analytical tool.

Detect Anomalies

Based on the daily cost data, this command will try to detect anomalies and trends. It will scan for the following anomalies:

  • Cost that is stopped; although it is good that the cost is stopped, it might be an indication that something is wrong.
  • Cost that is appearing; the cost was not there before and is now adding to the overall cost.
  • A spike in cost; a deviation from the normal cost pattern
  • A gradual increase in cost; so a service is growing in cost over time.

There are a number of

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#azureclicommand-linecost

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具