Skip to content

Instantly share code, notes, and snippets.

@dheerajinampudi
Created April 26, 2023 07:55
Show Gist options
  • Save dheerajinampudi/d27b2e5a73631361eb990c806277a65a to your computer and use it in GitHub Desktop.
Save dheerajinampudi/d27b2e5a73631361eb990c806277a65a to your computer and use it in GitHub Desktop.
get last 1 month's size of the s3 bucket
def get_bucket_size_from_cloudwatch(bucket_name, region_name):
cloudwatch = boto3.client('cloudwatch', region_name=region_name)
response = cloudwatch.get_metric_statistics(
Namespace='AWS/S3',
MetricName='BucketSizeBytes',
Dimensions=[{'Name': 'BucketName', 'Value': bucket_name}, {'Name': 'StorageType', 'Value': 'StandardStorage'}],
StartTime=datetime.utcnow() - timedelta(days=30),
EndTime=datetime.utcnow(),
Period=86400,
Statistics=['Average']
)
if datapoints := response.get('Datapoints', []):
return datapoints[-1]['Average']
else:
return 0
# %%
bucket_name = '316381694901-propellor'
region_name = 'ap-south-1'
bucket_size = get_bucket_size_from_cloudwatch(bucket_name, region_name)
# %%
bucket_in_GB = round(bucket_size/1000000000,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment