1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazon S3の各バケットの使用量一覧取得シェルスクリプト

Last updated at Posted at 2024-05-16

aws s3 ls でも使用量取得できるけど、オブジェクト数が多い場合にエコじゃないので違うやり方。
多分こんな感じ。
リージョンは必要に応じて追記してください。

#!/bin/sh

# 直近の値が分かれば良いので前日を指定
ymd=$(date '+%Y-%m-%d' --date '1 days ago')
start_time="${ymd}T00:00:00Z"
end_time="${ymd}T23:59:59Z"
period=86400

# 数値を人に優しくするよ
human_readable() {
  # 小数で渡ってくるので整数化
  num=$(echo $1 | awk '{printf("%d\n",$1)}')

  # 単位
  units=(B KB MB GB TB PB EB ZB YB)

  # 判定用の閾値
  thresholds=(1 1024 1048576 1073741824 1099571627776 1125899906884629 1152921504606846976 1180591620717411303424)

  # 処理
  i=1
  while [ $num -gt ${thresholds[$i]} ]; do
    i=$((i + 1))
  done
  i=$((i - 1))

  # 出力
  num=$(awk "BEGIN { print $num / ${thresholds[$i]} }")
  num_readable=$(printf "%.2f" "$num")
  echo "${num_readable}${units[$i]}"
}

# バケット名一覧取得
bucket_names=$(aws s3 ls | awk '{print $3}')

for bucket_name in ${bucket_names};
do
  # バケットごとの使用量取得
  bucket_size=$(aws cloudwatch get-metric-statistics \
  --namespace AWS/S3 \
  --metric-name BucketSizeBytes \
  --dimensions Name=BucketName,Value=${bucket_name} Name=StorageType,Value=StandardStorage \
  --statistics Sum \
  --start-time ${start_time} \
  --end-time ${end_time} \
  --period ${period} \
  --output text | awk '{printf $2}')
  bucket_size_readable=$(human_readable ${bucket_size})
  echo "s3://${bucket_name}/ size:${bucket_size_readable}"
done
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?