我希望从我的Lambda函数中获取EC2InstanceId,但不知何故我遇到了一个错误string indices must be integers: TypeError
这是代码:
from __future__ import print_function
import json
import re
import boto3
def lambda_handler(event, context):
"""
lambda handler function.
"""
message = event['Records'][0]['Sns']['Message']
print(message)
ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
print(ec2InstanceId)
但是,我从print(message)
得到以下输出:
{
"Progress": 50,
"AccountId": "*****************",
"Description": "Launching a new EC2 instance: i-0316df8d5159ee6a7",
"RequestId": "4b15abf1-7b48-4e9b-528a-891992eabc86",
"EndTime": "2019-05-28T02:57:46.975Z",
"AutoScalingGroupARN": "arn:aws:autoscaling:us-east-1:*****************:autoScalingGroup:*****************:autoScalingGroupName/dynamic-host-asg",
"ActivityId": "*****************",
"StartTime": "2019-05-28T02:57:13.747Z",
"Service": "AWS Auto Scaling",
"Time": "2019-05-28T02:57:46.975Z",
"EC2InstanceId": "i-0316df8d5159ee6a7",
"StatusCode": "InProgress",
"StatusMessage": "",
"Details": {
"Subnet ID": "*****************",
"Availability Zone": "us-east-1b"
},
"AutoScalingGroupName": "dynamic-host-asg",
"Cause": "At 2019-05-28T02:56:47Z a user request update of AutoScalingGroup constraints to min: 1, max: 2, desired: 1 changing the desired capacity from 0 to 1. At 2019-05-28T02:57:11Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1.",
"Event": "autoscaling:EC2_INSTANCE_LAUNCH"
}
但是print(ec2InstanceId)
给我以下错误:
string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 27, in lambda_handler
ec2InstanceId = event['Records'][0]['Sns']['Message']['EC2InstanceId']
TypeError: string indices must be integers
您能帮我解决这个问题吗?
答案 0 :(得分:0)
我让它像这样
message = event['Records'][0]['Sns']['Message']
if isinstance(message, str):
try:
message = json.loads(message)
except Exception as e:
print(e)
elif isinstance(message, list):
message = message[0]
asg_instances_list=message['EC2InstanceId']