Last active
August 3, 2022 19:31
-
-
Save ruandre/7703adb411409a3325dfaae32f8fe2f1 to your computer and use it in GitHub Desktop.
S3 Bucket Size
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
const AWS = require('aws-sdk') | |
const Promise = require('bluebird') | |
const filesize = require('filesize') | |
// AWS.config.update({ accessKeyId: '', secretAccessKey: '', region: '' }) | |
const s3 = new AWS.S3() | |
const cloudwatch = new AWS.CloudWatch() | |
const TWELVE_HOURS_IN_SECONDS = 43_200 | |
async function main() { | |
try { | |
const data = await s3.listBuckets().promise() | |
const bucketNames = data.Buckets.map(bucket => bucket.Name) | |
const sizes = await Promise.mapSeries(bucketNames, async bucketName => { | |
try { | |
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#getMetricStatistics-property | |
const opts = { | |
StartTime: new Date('2019-06-03T00:00:00'), | |
EndTime: new Date('2019-06-13T00:00:00'), | |
MetricName: 'BucketSizeBytes', | |
Namespace: 'AWS/S3', | |
Period: TWELVE_HOURS_IN_SECONDS, | |
Dimensions: [ | |
{ Name: 'BucketName', Value: bucketName }, | |
{ Name: 'StorageType', Value: 'StandardStorage' }, | |
], | |
Statistics: ['Maximum'], | |
} | |
const stats = await cloudwatch.getMetricStatistics(opts).promise() | |
const points = stats.Datapoints | |
if (typeof points.pop() === 'undefined') { | |
console.log(`${bucketName}: ${filesize(0)}`) | |
return 0 | |
} | |
console.log(`${bucketName}: ${filesize(points.pop().Maximum)}`) | |
return points.pop().Maximum | |
} catch (e) { | |
console.log(e) | |
} | |
}) | |
console.log(filesize(sizes.reduce((acc, curr) => acc + curr))) | |
} catch (e) { | |
console.log(e) | |
} | |
} | |
main() // run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment