Email notification through SNS and Lambda

风格不统一 提交于 2019-12-01 14:26:39

As shown in the Amazon CloudWatch Events console, a sample event triggered by an instance state change is:

{
  "version": "0",
  "id": "7bf73129-1428-4cd3-a780-95db273d1602",
  "detail-type": "EC2 Instance State-change Notification",
  "source": "aws.ec2",
  "account": "123456789012",
  "time": "2015-11-11T21:29:54Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
  ],
  "detail": {
    "instance-id": "i-abcd1111",
    "state": "pending"
  }
}

CloudWatch events can then directly trigger an AWS Lambda function, passing in this information.

The Lambda function can use the Instance ID to retrieve further details about the instance (eg server name, IP address).

The function can then either:

  • Send text to an Amazon SNS Topic, which can forward the information to subscribers (via email or SMS), OR
  • Send the emails via Amazon Simple Email Service (SES), which can send emails with complex formatting

Using SNS would be the easiest, if you don't mind the text-based content.

Here is some sample code that will receive an event from Amazon CloudWatch Events when an instance changes state, then send a message to an Amazon SNS topic with further details:

import boto3

def lambda_handler(event, context):

    # Extract Instance ID from event
    instance_id = event['detail']['instance-id']

    # Obtain information about the instance
    ec2_client = boto3.client('ec2')
    instance_info = ec2_client.describe_instances(InstanceIds=[instance_id])
    instance = instance_info['Reservations'][0]['Instances'][0]

    # Extract name tag
    name_tags = [t['Value'] for t in instance['Tags'] if t['Key']=='Name']
    name = name_tags[0] if name_tags is not None else ''

    # Send message to SNS
    MY_SNS_TOPIC_ARN = 'arn:aws:sns:ap-southeast-2:123456789012:foo'
    sns_client = boto3.client('sns')
    sns_client.publish(
        TopicArn = MY_SNS_TOPIC_ARN,
        Subject = 'Instance Change State: ' + instance_id,
        Message = 'Instance: ' + instance_id + ' has changed state\n' +
                  'State: ' + instance['State']['Name'] + '\n' +
                  'IP Address: ' + instance['PublicIpAddress'] + '\n' +
                  'Name: ' + name
    )

To setup:

  • Create an SNS topic to receive the message and put the topic ARN in the code
  • Create a subscriber to the SNS topic (easiest is via SMS when testing)
  • Create the AWS Lambda function (shown above)
  • Create an Amazon CloudWatch Event to trigger off EC2 instance state change, and set the target to the Lambda function
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!