feat: cloudfront-usage.py which calculates the usage of past 3 months

This commit is contained in:
xpk
2026-03-15 23:15:09 +08:00
parent a732a5c86f
commit 64290109a6
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
r"""
Documentation
License: This program is released under the MIT License
"""
# Imports
import boto3
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
# Main function
def main() -> None:
# get distributions
cw = boto3.client('cloudwatch', region_name='us-east-1')
cf = boto3.client('cloudfront', region_name='us-east-1')
distros = cf.list_distributions()['DistributionList']['Items']
dist_ids = [d['Id'] for d in distros if d['Status'] == 'Deployed']
for dist_id in dist_ids:
for month_offset in range(-3, 0): # Past 3 months
now = datetime.now()
first_of_current_month = now.replace(day=1)
start = (first_of_current_month + relativedelta(months=month_offset)).replace(day=1)
end = (start + relativedelta(months=1)) - relativedelta(seconds=1) # Last day
# BytesDownloaded
bytes_resp = cw.get_metric_statistics(
Namespace='AWS/CloudFront', MetricName='BytesDownloaded',
Dimensions=[{'Name': 'DistributionId', 'Value': dist_id}, {'Name': 'Region', 'Value': 'Global'}],
StartTime=start, EndTime=end, Period=2678400, Statistics=['Sum']
)
bytes_total = bytes_resp['Datapoints'][0]['Sum'] if bytes_resp['Datapoints'] else 0
# Requests
reqs_resp = cw.get_metric_statistics(
Namespace='AWS/CloudFront', MetricName='Requests',
Dimensions=[{'Name': 'DistributionId', 'Value': dist_id}, {'Name': 'Region', 'Value': 'Global'}],
StartTime=start, EndTime=end, Period=2678400, Statistics=['Sum']
)
reqs_total = reqs_resp['Datapoints'][0]['Sum'] if reqs_resp['Datapoints'] else 0
gb = round(bytes_total / (1024 ** 3), 2) if bytes_total else 0
# only interested in distro with high traffic
if gb > 10:
print(f"{dist_id} - Month: {start:%Y-%b} Requests: {reqs_total:,.0f} BytesDownloaded: {gb} GB")
# Call main function
if __name__ == '__main__':
main()