Skip to content

Instantly share code, notes, and snippets.

@RafaelWO
Last active November 15, 2024 13:37
Show Gist options
  • Save RafaelWO/8917d6b8618fa825304b706ea65ccbee to your computer and use it in GitHub Desktop.
Save RafaelWO/8917d6b8618fa825304b706ea65ccbee to your computer and use it in GitHub Desktop.
AWS: Calculate the size of all ECR repositories
repos=""
sizes=""
name_lens=""
# Check if user is logged in
if ! aws sts get-caller-identity &> /dev/null; then
echo "ERROR: Seems like your SSO session is invalid. Please run"
printf "\n $ aws sso login\n\n"
echo "before you run the script."
exit 1
fi
data=$(aws ecr describe-repositories --output json | jq .repositories)
repo_count=$(echo $data | jq length)
index=1
for name in $(echo $data | jq -r .[].repositoryName); do
# Progress
echo -en "\033[K"
echo -n "[$index/$repo_count] GET $name" $'\r'
# Get size
size=$(aws ecr describe-images --repository-name "$name" --output json | jq .imageDetails[].imageSizeInBytes | awk '{s+=$1}END{OFMT="%.0f";print s}')
if [ -n "$size" ]; then
raw_size="$size"
size=$(numfmt --to=iec --suffix=B --format "%.2f" $size)
else
raw_size="0"
size="<no-images>"
fi
repos="${repos}$name $size\n"
sizes="${sizes}$raw_size\n"
name_lens="${name_lens}${#name}\n"
index=$(expr $index + 1)
done
# Sort repos by size
repos=$(printf "$repos" | sort -k2 -h)
# Add separator before total
max_name_len=$(printf $name_lens | sort -n | tail -1)
repos="${repos}\n$(printf -- '-%.0s' $(seq ${max_name_len})) --------\n"
# Add total size
total=$(printf $sizes | awk '{s+=$1}END{OFMT="%.0f";print s}')
repos="${repos}TOTAL $(numfmt --to=iec --suffix=B --format "%.2f" $total)\n"
# Print final table
printf "$repos" | column -t --table-columns REPOSITORY,SIZE -R SIZE
@mohit2152sharma
Copy link

If you are on macos, you will also need to use gnumfmt instead of numfmt.

@matthill33
Copy link

Awesome script, I also had to use printf "$repos" | column -t -c REPOSITORY,SIZE for line #50

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment