Skip to content

Instantly share code, notes, and snippets.

@johnweldon
Created September 2, 2024 18:39
Show Gist options
  • Save johnweldon/a86633442df411fd07862c0819daa203 to your computer and use it in GitHub Desktop.
Save johnweldon/a86633442df411fd07862c0819daa203 to your computer and use it in GitHub Desktop.
Bash script to get last 3 months of AWS charges, and forecast for current month charges
#!/usr/bin/env bash
set -euo pipefail
TODAY="$(date "+%Y-%m-%d")"
NEXTM="$(date -v+1m "+%Y-%m-%d")"
THREE="$(date -v-3m "+%Y-%m-%d")"
BEGIN="${THREE:0:8}01"
END="${NEXTM:0:8}01"
COST_TIME_PERIOD='{"Start":"'${BEGIN}'","End":"'${TODAY}'"}'
ESTIMATE_TIME_PERIOD='{"Start":"'${TODAY}'","End":"'${END}'"}'
COST_Q='.ResultsByTime[]|"\(.TimePeriod.Start),\(.TimePeriod.End),\(.Total.BlendedCost.Unit),\(.Total.BlendedCost.Amount|tonumber|.*pow(10;2)|round/pow(10;2)),Cost"'
# shellcheck disable=SC2016
EST_Q='.Total.Unit as $unit | .ForecastResultsByTime[]|"\(.TimePeriod.Start),\(.TimePeriod.End),\($unit),\(.MeanValue|tonumber|.*pow(10;2)|round/pow(10;2)),Forecast"'
>&2 echo -en "\033[31;40mThis will cost \$0.02; continue?\033[0m "
read -n 1 -r REPLY
if [[ ! $REPLY =~ ^[Yy]$ ]]; then :
else
aws ce get-cost-and-usage \
--time-period "${COST_TIME_PERIOD}" \
--metric "BLENDED_COST" \
--granularity "MONTHLY" \
--output json | jq -r "${COST_Q}"
aws ce get-cost-forecast \
--time-period "${ESTIMATE_TIME_PERIOD}" \
--metric "BLENDED_COST" \
--granularity "MONTHLY" \
--output json | jq -r "${EST_Q}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment