Skip to content

Instantly share code, notes, and snippets.

@edtshuma
Forked from si3mshady/monitor_ec2_instance.py
Created June 9, 2023 12:44
Show Gist options
  • Save edtshuma/b408182218300e2cea9a824d4379d266 to your computer and use it in GitHub Desktop.
Save edtshuma/b408182218300e2cea9a824d4379d266 to your computer and use it in GitHub Desktop.
Setting Up CloudWatch Alarms with Boto3 to Monitor EC2 Instance Performance
import boto3
# Specify the region where the EC2 instances reside
region = 'us-east-1'
# Specify the tag key and value to filter the EC2 instances
tag_key = 'env'
tag_value = 'prod'
#Specify sns topic
sns_arn = "arn:aws:sns:us-east-1:335055665325:EC2_Alert"
# Specify the alarm thresholds for CPU and Memory utilization
cpu_threshold = 50.0
memory_threshold = 60.0
# Create a CloudWatch client
cloudwatch = boto3.client('cloudwatch', region_name=region)
# Get the list of EC2 instances with the specified tag
ec2_client = boto3.client('ec2', region_name=region)
response = ec2_client.describe_instances(
Filters=[
{
'Name': 'tag:' + tag_key,
'Values': [tag_value]
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
)
ec2 = boto3.client('ec2', region_name='us-east-1')
instance_ids = [instance['InstanceId'] for instance in ec2.describe_instances()['Reservations'][0]['Instances']]
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])
# Create CloudWatch alarms for CPU and Memory utilization for each EC2 instance
for instance_id in instance_ids:
# Create CPU utilization alarm
cloudwatch.put_metric_alarm(
AlarmName=f'CPUUtilizationAlarm-{instance_id}-sreuniversity',
ComparisonOperator='GreaterThanOrEqualToThreshold',
EvaluationPeriods=3,
Threshold=cpu_threshold,
Period=60,
Namespace='AWS/EC2',
MetricName='CPUUtilization',
Statistic='Average',
Dimensions=[
{
'Name': 'InstanceId',
'Value': instance_id
},
],
AlarmActions=[
sns_arn # Specify your SNS topic ARN here to receive notifications
]
)
# Create Memory utilization alarm
cloudwatch.put_metric_alarm(
AlarmName=f'MemoryUtilizationAlarm-{instance_id}-sreuniversity',
ComparisonOperator='GreaterThanOrEqualToThreshold',
EvaluationPeriods=3,
Threshold=memory_threshold,
Period=60,
Namespace='CWAgent',
MetricName='MemoryUtilization',
Statistic='Average',
Dimensions=[
{
'Name': 'InstanceId',
'Value': instance_id
},
],
AlarmActions=[
sns_arn # Specify your SNS topic ARN here to receive notifications
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment