0 amazon-web-services amazon-sns amazon-cloudwatch aws-lambda
我正面临一个问题。我的主要动机是在 ec2 实例发生状态更改时发送电子邮件。
我直接使用 SNS 尝试了云监视事件及其工作,但我收到的电子邮件模板没有正确的信息来理解。
我期待电子邮件模板中的服务器名称及其 IP,但 SNS 没有给我修改它的选项。所以我在想的是让 lambda 参与进来
如果您认为这是否符合我的期望,请告诉我。并就如何在 Cloud watch 和 SNS 之间获取 Lambda 提供一些见解
感谢和问候
如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"
}
}
Run Code Online (Sandbox Code Playgroud)
然后,CloudWatch 事件可以直接触发 AWS Lambda 函数,传入此信息。
Lambda 函数可以使用实例 ID 来检索有关实例的更多详细信息(例如服务器名称、IP 地址)。
然后该函数可以:
如果您不介意基于文本的内容,使用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
)
Run Code Online (Sandbox Code Playgroud)
建立:
| 归档时间: |
|
| 查看次数: |
9008 次 |
| 最近记录: |