【问题标题】:Boto3:TypeError: list indices must be integers or slices, not strBoto3:TypeError:列表索引必须是整数或切片,而不是 str
【发布时间】:2020-07-16 15:56:41
【问题描述】:

我正在尝试获取从 cloudformation 堆栈 创建的实例的私有 IP 地址 的值。我可以从响应输出中看到有关该实例的完整详细信息。但是,当我尝试 获取特定值,它会失败并出现错误'TypeError: list indices must be integers or slices, not str'

def update_hosts(Stack_Name):
    client = boto3.client('cloudformation')
    ec2 = boto3.client('ec2')
    stack_resources = client.list_stack_resources(StackName=Stack_Name)
    for resource in stack_resources['StackResourceSummaries']:
        if resource['ResourceType'] == 'AWS::EC2::Instance' and resource['ResourceStatus'] == 'CREATE_COMPLETE':
            instance = (resource['PhysicalResourceId'])
            response=ec2.describe_instances(InstanceIds=[instance])
            print(response['Reservations']['Instances']['ImageId'])

响应输出: {'Reservations': [{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'xxx', 'InstanceId': 'i-xxx', 'InstanceType': 'xxx',..................}}

错误输出:-'TypeError: list indices must be integers or slices, not str'

我有兴趣在输出中选择一个特定的值,比如 ImageId/InstanceId。 有人可以建议如何实现这一点。

【问题讨论】:

  • 请发布完整的回溯。很难判断错误在哪里。

标签: python amazon-web-services boto3


【解决方案1】:

基于文档 describe_instances ReservationsInstances 是列表

因此,您可以执行以下操作:

for reservation in response['Reservations']:
   for instance in reservation['Instances']:
     print(instance['ImageId'])

而不是

print(response['Reservations']['Instances']['ImageId'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多