Skip to content

Instantly share code, notes, and snippets.

@lucagrulla
Last active January 23, 2018 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucagrulla/c26645b19ef5d3b4289b01fd6a50d2b1 to your computer and use it in GitHub Desktop.
Save lucagrulla/c26645b19ef5d3b4289b01fd6a50d2b1 to your computer and use it in GitHub Desktop.
S3 buckets size
require 'aws-sdk-cloudwatch'
require 'aws-sdk-s3'
START_DATE = Time.new(2018,1,21).utc
END_DATE = Time.new(2018,1,22).utc
REGION = "eu-west-1"
CW = Aws::CloudWatch::Client.new(region: REGION)
S3 = Aws::S3::Resource.new(region: REGION)
def bytes_to_s(s)
return "0 bytes" if s.nil?
suffix = "bytes"
if s >= 1024
s = (s/1024).to_f
suffix = "kb"
end
if s >= 1024
s = (s/1024).to_f
suffix = "MB"
end
if s >= 1024
s = (s/1024).to_f
suffix = "GB"
end
if s >= 1024
s = (s/1024).to_f
suffix = "TB"
end
"#{s.round(2)} #{suffix}"
end
def get_size(bucket)
a = CW.get_metric_statistics({namespace: "AWS/S3", metric_name:"BucketSizeBytes", dimensions: [{name:'StorageType', value:'StandardStorage'},
{name:"BucketName", value:bucket}],
start_time: START_DATE, end_time: END_DATE,
period:86400, statistics:["Maximum"], unit: "Bytes"}).datapoints.first
return 0 if a.nil?
a.maximum
end
buckets = S3.buckets.map{|b| b.name}
puts "buckets #: #{buckets.count}"
tot = buckets.reduce({}){|acc, b| acc[b] = get_size(b); acc}
tot.sort_by{|_, v| -v}.each do |k, v|
puts "#{k}: #{bytes_to_s(v)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment