Created
March 8, 2025 07:12
-
-
Save ariel-frischer/ae7bbed73ed8d8abfb9ea129bfad2929 to your computer and use it in GitHub Desktop.
aws bash script to get simple cost tables for the last 7 days
This file contains hidden or 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