如 Amazon CloudWatch Events 控制台所示,由实例状态更改触发的示例事件是:
{
"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 事件随后可以直接触发 AWS Lambda 函数,并传入此信息。
Lambda 函数可以使用实例 ID 检索更多详细信息关于实例(例如服务器名称、IP 地址)。
然后该函数可以:
- 向Amazon SNS 主题 发送文本,该主题可以将信息转发给订阅者(通过电子邮件或短信),或
- 通过Amazon Simple Email Service (SES)发送电子邮件,该服务可以发送格式复杂的电子邮件
如果您不介意基于文本的内容,使用 SNS 将是最简单的。
以下是一些示例代码,当实例更改状态时,它们将从 Amazon CloudWatch Events 接收事件,然后向 Amazon SNS 主题发送消息,并提供更多详细信息:
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
)
设置:
- 创建一个 SNS 主题来接收消息并将主题 ARN 放入代码中
- 为 SNS 主题创建订阅者(最简单的方法是在测试时通过 SMS)
- 创建 AWS Lambda 函数(如上所示)
- 创建 Amazon CloudWatch 事件以触发 EC2 实例状态更改,并将目标设置为 Lambda 函数