首页 > 解决方案 > “TypeError:字符串索引必须是整数,而不是 str”在 boto3 aws 执行期间

问题描述

我正在尝试使用 Boto3 的describe_instance方法获取 AWS 的 VM 列表。我收到以下错误。

Traceback (most recent call last):
  File "pySkynet2.py", line 238, in <module>
    skynet.execute()
  File "pySkynet2.py", line 126, in execute
    self.verify('build')
  File "pySkynet2.py", line 77, in verify
    vm_list = self.cloud_forge.get_vm_list()
  File "/Users/ssrini358/workplace/Codes/COM_codes/Skynet/api2/cloudforge.py", line 952, in get_vm_list
    instance = self.get_instance(auto_instance['Reservations'][0]['Instances'][0]['InstanceId'])
TypeError: string indices must be integers, not str

以下是代码片段。

    def get_vm_list(self):
        """
        look up all the instances for the cluster (autoscaling_group)
        :return: a list of associative arrays containing the instance_id, ip address and host name
        """
        try:
            instances = self.get_instances_for_autoscaling_group()
            vms = []
            for auto_instance in instances:
                instance = self.get_instance(auto_instance['Reservations'][0],['Instances'][0],['InstanceId'])
                host_name = ''
                for tag in instance['Reservations'][0]['Instances'][0]['Tags']:
                    if tag['Key'] == 'Name':
                        host_name = tag['Value']
                        break

                vms.append({'instance_id': instance['Reservations'][0]['Instances'][0]['InstanceId'],
                            'ip_addr': instance['Reservations'][0]['Instances'][0]['PrivateIpAddress'],
                            'host_name': host_name})

            return vms

我也试过 ['Reservations'][0]。但我无法获得instanceId。请帮助 TIA

标签: pythonamazon-web-servicesboto3aws-cli

解决方案


既然你已经分配了实例,不应该是这样吗?

instances = self.get_instances_for_autoscaling_group()
vms = []
for auto_instance in instances:
    instance = self.get_instance(auto_instance['Reservations'][0],['Instances'][0],['InstanceId'])
    host_name = ''
    for tag in instance:

推荐阅读