Last active
May 24, 2023 03:30
-
-
Save quangnhut123/d66e49c0414200c7ed686ffd796ca53d to your computer and use it in GitHub Desktop.
Check ECR Cost and Usage
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
#!/bin/bash | |
export AWS_REGION=ap-northeast-1 | |
process_profile() { | |
local profile=$1 | |
echo -e "\n\n========== Processing profile: $profile ==========" | |
export AWS_PROFILE=$profile | |
# Get the ECR cost and usage for the current month | |
local start_date=$(date -v1d +%Y-%m-%d) | |
local end_date=$(date -v1d -v+1m -v-1d +%Y-%m-%d) | |
local cost_usage=$(aws ce get-cost-and-usage --time-period Start=$start_date,End=$end_date --granularity MONTHLY --metrics "BlendedCost" "UsageQuantity" --filter "Dimensions={Key=SERVICE,Values='Amazon EC2 Container Registry (ECR)'}" --output text --query 'ResultsByTime[0].Total.[BlendedCost.Amount, UsageQuantity.Amount]' 2>/dev/null) | |
if [[ -z "$cost_usage" ]]; then | |
echo "Failed to get ECR cost and usage" | |
return | |
fi | |
local cost=$(echo "$cost_usage" | awk '{print $1}') | |
local usage=$(echo "$cost_usage" | awk '{print $2}') | |
echo "ECR Cost for this month: $cost" | |
echo "ECR Usage Quantity (GB/month): $usage" | |
# Get a list of all ECR repositories | |
local repositories=$(aws ecr describe-repositories --query 'repositories[*].repositoryName' --output text 2>/dev/null) | |
# Iterate over each repository and get the image count | |
for repo in $repositories; do | |
local image_count=$(aws ecr describe-images --repository-name "$repo" --query 'length(imageDetails)' 2>/dev/null) | |
echo "Repository: $repo | Image Count: $image_count" | |
done | |
} | |
while IFS='' read -r line || [[ -n "$line" ]]; do | |
if [[ $line =~ ^\[(.*)\]$ ]]; then | |
process_profile "${BASH_REMATCH[1]}" | |
fi | |
done < "$1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment