Skip to content

Instantly share code, notes, and snippets.

@michabbb
Created September 1, 2024 12:46
Show Gist options
  • Save michabbb/3ba3b4a196d350c05deeae2d74903eba to your computer and use it in GitHub Desktop.
Save michabbb/3ba3b4a196d350c05deeae2d74903eba to your computer and use it in GitHub Desktop.
AWS: Get Costs by Customer (based on Tags) for the last month
#!/bin/bash
customer=$1
if [ -z "$customer" ]; then
echo "Error: No customer name provided. Please provide a customer name as the first argument." >&2
exit 1
fi
# Set your AWS credentials here
AWS_ACCESS_KEY_ID="xxxxxxxxxxx"
AWS_SECRET_ACCESS_KEY="xxxxxxxxxxxxxxxxxxx"
AWS_DEFAULT_REGION="us-east-1" # Set this to any region, e.g. us-east-1
# Set the date for the last month
current_date=$(date +%Y-%m-%d)
start_date=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m-%d)
end_date=$(date -d "$(date +%Y-%m-01)" +%Y-%m-%d)
echo "Query period: $start_date to $end_date"
# Docker command to run the AWS CLI command
docker run --rm -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
-e AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION \
amazon/aws-cli ce get-cost-and-usage \
--time-period Start=$start_date,End=$end_date \
--granularity MONTHLY \
--metrics "BlendedCost" "UsageQuantity" \
--group-by Type=DIMENSION,Key=REGION \
--filter "{\"Tags\": {\"Key\": \"customer\", \"Values\": [\"$customer\"]}}" \
--output json > output.json
# Extract the amount with 'jq'
amount=$(cat output.json | jq -r '.ResultsByTime[0].Groups[0].Metrics.BlendedCost.Amount')
echo "Amount in USD: $amount"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment