Skip to content

Instantly share code, notes, and snippets.

@hetul99
Created March 24, 2023 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hetul99/dc5aa750f61786767c73746036a5999a to your computer and use it in GitHub Desktop.
Save hetul99/dc5aa750f61786767c73746036a5999a to your computer and use it in GitHub Desktop.
import boto3
import json
def lambda_handler(event, context):
print("Received event: " + json.dumps(event))
if event['detail']['eventName'] == 'ModifyInstanceAttribute' and 'instanceType' in event['detail']['requestParameters']:
instance_id = event['detail']['requestParameters']['instanceId']
instance_type = event['detail']['requestParameters']['instanceType']['value']
cw = boto3.client('cloudwatch')
alarms = cw.describe_alarms()
for alarm in alarms['MetricAlarms']:
if alarm['Dimensions'][0]['Value'] == instance_id and alarm['Namespace'] == 'CWAgent' and alarm['MetricName'] == 'Memory % Committed Bytes In Use':
alarm_name = alarm['AlarmName']
print("Found alarm: " + alarm_name)
response = cw.put_metric_alarm(
AlarmName=alarm_name,
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=1,
MetricName='Memory % Committed Bytes In Use',
Namespace='CWAgent',
Period=300,
Statistic='Average',
Threshold=80.0,
ActionsEnabled=False,
AlarmDescription='Alarm when server Memory exceeds 80%',
Dimensions=[
{
'Name': 'InstanceId',
'Value': instance_id
},
{
'Name': 'InstanceType',
'Value': instance_type
},
],
)
print("Updated alarm: " + alarm_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment