AWS Lambda with CloudWatch for Seamless EC2 State Change Notifications through SES.

Venkateswara Reddy - Dec 9 '23 - - Dev Community

Creation of IAM:

  1. Search for iam in the console and create an IAM select lamda and then under policies search for ses and assign ses full access and again search for cloudwatch and then choose cloudwatch full access also then create a role by entering the role name.

Creation of EC2 :

  1. Create one EC2 instance.

Creation of SES:

  1. Search for SES then click on SES and fron the left side we have to select Email addresses and then click on verify a new email address.
  2. Enter the name of the email address and send a request. The receipient should accept the request then only our SES will come to veryfying state otherwise that will be in the pending stste only.
  3. NOTE: Amazon recently updated SES service we have to search for SES in the console and from left side we have to click on verified identities then create a new identity and choose email then enter our mail address and create no need to click anything else.

Creation of Lambda Function:

  1. Search for lambda in the console and click on the function and create a function bby selecting runtime as python and under role select from the existing role what ever we created earlier.
  2. Create the code and test.
  3. Here we are sending this mail to 3 receipients and also source is venkyy82@gmail.com

import json
import boto3

def lambda_handler(event, context):
    subject="Attention Please" 
    client=boto3.client('ses')
    body="""
         <br>
         This mail is comming from aws lambda Event Trigger.
         production server is down!!
         """
    message={"Subject":{"Data":subject},"Body":{"Html":{"Data":body}}}
    response=client.send_email(Source="venkyy82@gmail.com",Destination={"ToAddresses":["venkyy82@gmail.com","venkat.yeduru@gmail.com","venkateswarareddy227@gmail.com"]},Message=message)
    print("This mail is sent Successfully")

Enter fullscreen mode Exit fullscreen mode

Creation of cloudwatch event trigger:

  1. Search for cloudwatch in the console and from the leftt hand side we have to select the Rule under events.
  2. Select the event pattern and then under service name search for ec2 and event type is ec2 (termination.) ec2 instance state change notification.
  3. Then select specififc state under that we have to select stopped and any ec2 instance/specific ec2 instance we can select specific ec2 instance under that we have to add ec2 instance_ID.
  4. Create trigger then choose lamda select what is our lambda function nmae and create the rule.
  5. While creating cloudwatch rule we can select ec2 under this ec2 many events will be there. we can choose what ever we want.
. . . . . . . . . . . . .