【发布时间】:2021-01-07 10:33:41
【问题描述】:
我希望如果我的 ec2 的状态发生变化,那么我将收到一个 SNS,其中包含 ec2 名称、实例 ID 和帐户名称、区域。
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
)
出现以下错误...
START RequestId:7c29aec4-2d51-4b29-91a0-8fc1217397ce 版本:$LATEST “细节”:KeyError 回溯(最近一次通话最后): 文件“/var/task/lambda_function.py”,第 6 行,在 lambda_handler instance_id = event['detail']['instance-id'] KeyError:“详细信息”
【问题讨论】:
-
你是如何调用函数的?您是否按照Email notification through SNS and Lambda 创建了 CloudWatch 事件?该函数似乎没有从 CloudWatch Events 接收事件信息。
-
能否在函数处理程序的开头添加
print(event)并检查事件对象结构?
标签: amazon-web-services amazon-ec2 aws-lambda