Home > Software design >  python lambda code for aws ec2 gets stopped
python lambda code for aws ec2 gets stopped

Time:10-09

could any one please help me the lambda code , whenever AWS Ec2 instances get stopped, we need to get the email notifications with sns. In the email we need instance name. I could able to get instance id but not the instance name.

CodePudding user response:

AWS CloudTrail allows you to identify and track EC2 instance lifecycle API calls (launch, start, stop, terminate). See How do I use AWS CloudTrail to track API calls to my Amazon EC2 instances?

And you can trigger a Lambda function to run arbitrary code when CloudTrail logs certain events. See Triggering a Lambda function with AWS CloudTrail events.

You can also create an Amazon CloudWatch alarm that monitors an Amazon EC2 instance and triggers a Lambda via CloudWatch Events.

CodePudding user response:

You can create a rule in Amazon CloudWatch Events that:

  • Triggers when an instance enters the Stopped state
  • Sends a message to an Amazon SNS Topic

Like this:

Amazon CloudWatch Events rule

If you want to modify the message that is being sent, then configure the Rule to trigger an AWS Lambda function instead. Your function should:

  • Extract the instance information (eg InstanceId) from the event parameter
  • Call describe-instances to obtain the Name of the instance (presumably the Tag with a Key of Name)
  • Publish a message to the Amazon SNS Topic
  • Related