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
' +
'State: ' + instance['State']['Name'] + '
' +
'IP Address: ' + instance['PublicIpAddress'] + '
' +
'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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…