我希望,如果我的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
)正在获取以下错误...
启动任务: 7c29aec4-2d51-4b29-91a0-8fc1217397ce版本:$LATEST 'detail':KeyError回溯(最近一次调用):文件“/var/RequestId/lambda_function.py”,第6行,in lambda_handler instance_id =KeyError 'detail‘KeyError:’detail‘
发布于 2020-09-21 19:03:01
是否按cloudwatch事件创建触发器,是否根据EC2实例状态变化创建cloudwatch事件?
乍一看,事件模式预览是
{
"source": [
"aws.ec2"
],
"detail-type": [
"EC2 Instance State-change Notification"
]
}因此,请与上述检查,并提供有关您的案例的更多信息。
https://stackoverflow.com/questions/63990434
复制相似问题