Skip to content

Instantly share code, notes, and snippets.

@zoltanctoth
Last active April 7, 2025 23:26
Show Gist options
  • Select an option

  • Save zoltanctoth/eb3ff39efe779a7790e94f3b387827f7 to your computer and use it in GitHub Desktop.

Select an option

Save zoltanctoth/eb3ff39efe779a7790e94f3b387827f7 to your computer and use it in GitHub Desktop.
A simple script to approximate Azure spendings. This is far from accurate. Please comment if you know a better way
#! /usr/bin/env bash
set -e
DAILY_SPENDING_LIMIT=3 # USD, per account
DATE_COMMAND="date"
if hash gdate 2>/dev/null
then
DATE_COMMAND="gdate"
fi
subscriptions="$(az login -u "${AZURE_USERNAME}" -p "${AZURE_PASSWORD}" | jq -r '.[] | .id')"
get_costs () {
subscription="$1"
start_date="$2"
end_date="$3"
az account set --subscription "$subscription"
# the sed piece converts scientific notation to a format that can be processed by `bc`
# see https://stackoverflow.com/a/12882612/231644
tmp_file="$(mktemp)"
az consumption usage list --start-date "$start_date" --end-date "$end_date" | jq -r '.[] | .pretaxCost' \
| sed -E 's/([+-]?[0-9.]+)[eE]\+?(-?)([0-9]+)/(\1*10^\2\3)/g' >> "$tmp_file"
cost=$(paste -sd+ "$tmp_file" | bc | head -1 | sed 's/\\$//')
rm -f "$tmp_file"
printf "%.2f\n" "$cost"
}
for s in $subscriptions
do
cost=$(get_costs "$s" "$($DATE_COMMAND --date='1 day ago' +%Y-%m-%d)" "$($DATE_COMMAND --date='today' +%Y-%m-%d)")
if (( $(echo "$cost > "$DAILY_SPENDING_LIMIT"" | bc -l) )); then
message="<!channel> :warning: Azure account ${s}\\n *Current cost \$$cost*. Cost since yesterday exceeds threshold \$${DAILY_SPENDING_LIMIT}."
else
message="ALL OK Azure account ${s}\\n *Current cost \$$cost* threshold \$${DAILY_SPENDING_LIMIT}."
fi
# Send to slack
...
done
@TiloGit

TiloGit commented Apr 7, 2025

Copy link
Copy Markdown

i used this for a while:

###list pretaxCost for all subs
billingperiod=$(date -d "$date -1 month" +"%Y%m")
for sub in $(az account list --query "[].id" -o tsv)
do
cost=$(az consumption usage list -m --query "[].pretaxCost.to_number(@) | sum([])" --billing-period-name $billingperiod --subscription $sub --only-show-errors)
costRound=$(printf "%.2f" $cost)
echo "$sub $costRound"
done

but broke for two reasons:
(400) Billing Period is not supported in (2023-05-01) API Version for Subscription Scope With Web Direct Offer. Please provide the UsageStart and UsageEnd dates in the $filter key as parameters. (Request ID: 0e1a4968-5a97-4acb-a401-c0zzzzzz871) Code: 400

but with stat and end date now face this: Azure/azure-cli#28323

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment