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.
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.
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:
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=[
for tag in response[‘Tags’]:
if (tag[‘Key’] == tag_key and tag[‘Value’] ==tag_value):
var_condition = True
if (event_detail[‘state’] == ‘running’):
AlarmName=’Quoting_app_’ + event_detail[‘instance-id’],
elif (event_detail[‘state’] == ‘terminated’):
AlarmNames=[‘Quoting_app_’ + event_detail[‘instance-id’]]
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.
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
• CloudFormation template – Use stack sets to deploy across multiple regions.
"*" indicates required fields
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.