Last active
April 15, 2024 13:37
-
-
Save Alex-Just/60d68f825365b7df01976d9324a62080 to your computer and use it in GitHub Desktop.
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
""" | |
The script fetches and prints the average CPU utilization for a given AWS RDS instance ID for the past specified months | |
""" | |
from datetime import datetime, timedelta | |
import boto3 | |
# Configuration | |
INSTANCE_ID = '...' | |
REGION_NAME = '...' | |
NAMESPACE = 'AWS/RDS' | |
METRIC_NAME = 'CPUUtilization' | |
PAST_MONTHS = 5 | |
def get_first_day_of_month(date): | |
"""Returns the first day of the month for the given date.""" | |
return datetime(date.year, date.month, 1) | |
def get_last_day_of_month(date): | |
"""Returns the last day of the month for the given date.""" | |
if date.month == 12: | |
return datetime(date.year, date.month, 31) | |
return datetime(date.year, date.month + 1, 1) - timedelta(days=1) | |
def fetch_monthly_average_cpu_utilization(instance_id, months=4): | |
"""Fetches and prints the average CPU utilization for the given instance ID for the past specified months.""" | |
cloudwatch = boto3.client('cloudwatch', region_name=REGION_NAME) | |
end_date = datetime.utcnow() | |
monthly_averages = [] | |
for month_delta in range(months, 0, -1): | |
# Calculate the first and last day of each month | |
month_start = get_first_day_of_month(end_date - timedelta(days=30 * month_delta)) | |
month_end = get_last_day_of_month(month_start) | |
try: | |
response = cloudwatch.get_metric_statistics( | |
Namespace=NAMESPACE, | |
MetricName=METRIC_NAME, | |
Dimensions=[{'Name': 'DBInstanceIdentifier', 'Value': instance_id}], | |
StartTime=month_start.isoformat(), | |
EndTime=month_end.isoformat(), | |
Period=2592000, # One month in seconds | |
Statistics=['Average'], | |
) | |
except Exception as e: | |
print(f"An error occurred while fetching metrics: {e}") | |
continue | |
# Check if there are data points for the month | |
if response['Datapoints']: | |
monthly_average = response['Datapoints'][0]['Average'] | |
monthly_averages.append((month_start.strftime('%Y-%m'), monthly_average)) | |
print(f"Month: {month_start.strftime('%Y-%m')}, Average CPU Utilization: {monthly_average}%") | |
else: | |
print(f"No data available for {month_start.strftime('%Y-%m')}") | |
return monthly_averages | |
if __name__ == "__main__": | |
monthly_averages = fetch_monthly_average_cpu_utilization(INSTANCE_ID, months=PAST_MONTHS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment