AWS Lambda Integration With EventBridge

      
   
                                                         

In our previous blog, we explored the concept of Lambda versioning. In real-world scenarios, Lambda functions are typically triggered either on a schedule or in response to specific events. In this post, we’ll walk through how to invoke a Lambda function using both scheduled triggers and event-driven mechanisms.

This is our goal. Our lambda scans for any RUNNING, PENDING instances of type "T3.SMALL". If there are any instances of that type, it triggers an email.

Involved services:

1) Lambda - Python code to scan for RUNNING, PENDING instances of type "T3.SMALL"

2) Event Bridge - Scheduler and Event Based.

3) SNS - Notification Service.

Here is the simple lambda code:

import boto3
import json


def lambda_handler(event,context):
    ec2 = session.client('ec2')

    # Define the instance type that should not be used
    target_instance_type = 't3.small'

    # Describe all running instances
    response = ec2.describe_instances(
        Filters=[
            {'Name': 'instance-state-name', 'Values': ['running']},
            {'Name': 'instance-type', 'Values': [target_instance_type]}
        ]
    )
    instances = []
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instances.append(instance['InstanceId'])
    if len(instances) !=0:
        message = f"Instance(s) ID: {instances} of type {target_instance_type} are running. Please change the instance type."
        #Invoke SNS
        sns = session.client('sns', region_name='us-east-1')
        topic_arn = 'arn:aws:sns:us-east-1:289880680865:instance_monitor_by_type'
        try:
            sns_response= sns.publish(
                TopicArn=topic_arn,
                Message=message,
                Subject='Alert: Instances Running On Type T3 SMALL'
            )
            #print(sns_response)
        except Exception as e:
            print(f"Failed to send email {e}")
    else:
        print(f"No Instances(s) running of type {target_instance_type}.")

Now we have our lambda function ready. Lets create event bridge scheduler.

We start with the rule name, schedule and which lambda function to be triggered.


We can schedule on regular intervals or based on a pattern like CRON.




Under target section, I am pointing to the lambda function I deployed.

Finally, We create a SNS - Topic with email as the protocol and confirm the subscription.



From our schedule, the lambda is invoked for every 5 minutes and if condition matches it triggers an email. Let's test it by creating EC2 instances of type "T3.SMALL"





The instance ID's are matching with the email. 



Comments

Popular posts from this blog

K8s - ETCD

SRE/DevOps Syllabus

K8s - Deployment and HPA replicas