Last active
February 23, 2025 06:55
-
-
Save ariel-frischer/719800265ea5c95bea5cf624511746a4 to your computer and use it in GitHub Desktop.
Pretty print aws usage per service for last 7 days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
# Get cost and usage data from AWS Cost Explorer | |
result=$(aws ce get-cost-and-usage --no-cli-pager \ | |
--time-period Start=$(date -d '7 days ago' '+%Y-%m-%d'),End=$(date '+%Y-%m-%d') \ | |
--granularity DAILY \ | |
--metrics "BlendedCost" "UsageQuantity" \ | |
--group-by Type=DIMENSION,Key=SERVICE) | |
# Iterate over each day in the results | |
while IFS= read -r day; do | |
start=$(echo "$day" | jq -r '.TimePeriod.Start') | |
end=$(echo "$day" | jq -r '.TimePeriod.End') | |
echo "Date: $start to $end" | |
printf "%-40s | %-20s | %-25s\n" "SERVICE" "BLENDED COST(USD)" "USAGE" | |
printf -- '%.0s-' {1..90}; echo | |
total_cost=0 | |
total_usage=0 | |
usage_unit="" | |
# Process each group for the day | |
mapfile -t groups < <(echo "$day" | jq -c '.Groups[]') | |
for group in "${groups[@]}"; do | |
service=$(echo "$group" | jq -r '.Keys[0]') | |
cost=$(echo "$group" | jq -r '.Metrics.BlendedCost.Amount') | |
usage=$(echo "$group" | jq -r '.Metrics.UsageQuantity.Amount') | |
unit=$(echo "$group" | jq -r '.Metrics.UsageQuantity.Unit') | |
if [ -z "$usage_unit" ]; then | |
usage_unit="$unit" | |
fi | |
total_cost=$(awk "BEGIN {printf \"%.10f\", $total_cost + $cost}") | |
total_usage=$(awk "BEGIN {printf \"%.10f\", $total_usage + $usage}") | |
printf "%-40s | %-20s | %-25s\n" "$service" "$cost" "$usage ($unit)" | |
done | |
printf -- '%.0s-' {1..90}; echo | |
printf "%-40s | %-20s | %-25s\n" "TOTAL" "$total_cost" "$total_usage ($usage_unit)" | |
echo "" | |
done < <(echo "$result" | jq -c '.ResultsByTime[]') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a simpler way check on billing, without having to log into AWS console daily (with MFA auth).
Output looks like this: