Skip to content

Instantly share code, notes, and snippets.

@zoltanctoth
Last active February 9, 2020 11:34
Show Gist options
  • Save zoltanctoth/eb3ff39efe779a7790e94f3b387827f7 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment