Files
aws-inventory/aws-s3.py
T
2026-01-23 17:03:29 +08:00

71 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python3
r"""
Documentation
License: This program is released under the MIT License
"""
# Imports
import boto3
from openpyxl import load_workbook
import datetime
def getBucketSize(bucket: str) -> int:
"""
Get size of a s3 bucket through cloudwatch metric
:param bucket:
:return: Bucket size in MiB
"""
s3 = boto3.client('s3')
region = s3.get_bucket_location(Bucket=bucket)['LocationConstraint']
if region is None:
region='us-east-1'
cloudwatch_client = boto3.client('cloudwatch', region_name=region)
response = cloudwatch_client.get_metric_statistics(Namespace='AWS/S3',
MetricName='BucketSizeBytes',
Dimensions=[
{
'Name': 'BucketName',
'Value': bucket
},
{
'Name': 'StorageType',
'Value': 'StandardStorage'
}
],
StartTime=datetime.datetime.now() - datetime.timedelta(
days=7),
EndTime=datetime.datetime.now(),
Period=86400,
Statistics=['Average']
)
if len(response['Datapoints']) == 0:
return 0
else:
return int(response['Datapoints'][0]['Average']/1024/1024/1024)
# Main function
def main() -> None:
# Open spreadsheet and add a sheet
wb = load_workbook('aws-inventory.xlsx')
ws = wb.create_sheet("S3")
s3_client = boto3.client('s3')
# Get the list of all buckets
response = s3_client.list_buckets()
# Print the names of the buckets
ws.append(['Buckets', 'SizeGiB'])
for bucket in response['Buckets']:
ws.append([bucket["Name"], getBucketSize(bucket["Name"])])
wb.save('aws-inventory.xlsx')
# Call main function
if __name__ == '__main__':
main()