The aim of the project is to automatically create CloudWatch alarms for existing and newly launched EC2 instances under the same project based on tag Key/Value pair. The CloudWatch alarms will also be automatically deleted when the instances are terminated.
Key = project_name/Value = quoting_app
The implementation will be done using the below AWS services.
Flow Diagram
Event for running instances:
EventBridge Rule and Pattern
If the event matches with the pattern, EventBridge invokes the targets. The targets are invoked in parallel.
EventBridge Targets
3. When the lambda function is triggered, it decides on whether to create a CloudWatch alarm or delete an existing CloudWatch alarm based on the information contained in detail.state (running or terminated).
Lambda Function Code: import json import boto3
EC2client = boto3.client (‘ec2’) CWclient = boto3.client (‘cloudwatch’)
def lambda_handler(event, context):
event_source = event[‘source’] event_detail = event[‘detail’]
tag_key = ‘project_name’ tag_value = ‘quoting_app’
var_condition = False
response = EC2client.describe_tags(Filters=[ { ‘Name’: ‘resource-id’, ‘Values’: [event_detail[‘instance-id’]] } ] )
for tag in response[‘Tags’]: if (tag[‘Key’] == tag_key and tag[‘Value’] ==tag_value): var_condition = True break else: print(‘False’)
if var_condition: if (event_detail[‘state’] == ‘running’): print(‘Running’) CWclient.put_metric_alarm( AlarmName=’Quoting_app_’ + event_detail[‘instance-id’], ActionsEnabled=True, AlarmActions=[ ‘arn:aws:sns:eu-west-1:623203908833:JB-Test-SNS’ ], MetricName=’CPUUtilization’, Namespace=’AWS/EC2′, Statistic=’Average’, Dimensions=[ { ‘Name’: ‘InstanceId’, ‘Value’: event_detail[‘instance-id’] }, ], Period=300, EvaluationPeriods=2, DatapointsToAlarm=1, Threshold=80, ComparisonOperator=’GreaterThanOrEqualToThreshold’, TreatMissingData=’breaching’ ) elif (event_detail[‘state’] == ‘terminated’): print(‘Terminated’) CWclient.delete_alarms( AlarmNames=[‘Quoting_app_’ + event_detail[‘instance-id’]] ) else: print(‘Skipped’)
In the console you will have created an EC2 instance and a CloudWatch alarm created automatically with the instance ID appended to the alarm name.
EC2 Console
CloudWatch Console
Reference documents: 1]. Tutorial: Get started with Amazon EC2 Linux instances: Tutorial: Get started with Amazon EC2 Linux instances – Amazon Elastic Compute Cloud 2]. Creating Amazon EventBridge rules that react to events: Creating Amazon EventBridge rules that react to events – Amazon EventBridge 3]. Getting started with Lambda: Getting started with Lambda – AWS Lambda 4]. Using Amazon CloudWatch metrics: Use Amazon CloudWatch metrics – Amazon CloudWatch 5]. Using Amazon CloudWatch alarms: Using Amazon CloudWatch alarms – Amazon CloudWatch
Next Steps: • CloudFormation template – Use stack sets to deploy across multiple regions.
"*" indicates required fields
By providing your information to Altron you are providing consent for the processing of your personal information. Refer to the Altron Privacy Policy for details on how Altron collects and uses your personal information.
By ticking the box, you provide consent to receive electronic marketing communication on Altron Solutions and Services and the solutions of our key strategic partners. You may personalize your subscriptions based on your interests.
You can manage your communication preferences or opt-out via the Altron website.