Boto3 AttributeError:'dict'对象没有属性'tags'

时间:2019-02-27 14:42:40

标签: python python-3.x boto3

运行脚本时出现错误:AttributeError: 'dict' object has no attribute 'tags'

这是我的代码:

import sys
import boto3
ec2 = boto3.client('ec2')
instance_id_list = input("Enter an instance ID separated by commas: ")
instance_ids = instance_id_list.split(",")
print("Deleting Instance IDs:")
for instance_id in instance_ids:
    instance = ec2.describe_instances(
        InstanceIds=[instance_id]
    ) ['Reservations']

    #ec2info = defaultdict()
    #for tag in instance.tags:
    #    if 'Name'in tag['Key']:
    #         print(tag['Key'])
    #        name = tag['Value']
    # Add instance info to a dictionary    \
    print(instance.get('Instances'))
    ec2info[instance.id] = {
        'Name': instance.get('Reservations').get('Instances').get('InstanceId'),
        'Instance ID': instance.id,
        'Type': instance.instance_type,
        'State': instance.state['Name'],
        'Private IP': instance.private_ip_address,
        'Public IP': instance.public_ip_address,
        'Launch Time': instance.launch_time
        }


attributes = ['Name', 'Instance ID', 'Type',
              'State', 'Private IP', 'Public IP', 'Launch Time']
for instance_id, instance in ec2info.items():
    for key in attributes:
        print("{0}: {1}".format(key, instance[key]))
        #print(instance.terminate())
        print("------")

这是我的脚本的完整输出:

        Enter an instance ID separated by commas: i-024d1b8e8eaa8e417,i-03804b280877175be
    Deleting Instance IDs:
    Traceback (most recent call last):
      File ".\aws_ec2_terminate_instances.py", line 13, in <module>
        for tag in instance.tags:

AttributeError: 'dict' object has no attribute 'tags'

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

需要2个修复程序

1)附加[0]['Instances'][0]以获得实例详细信息

instance = ec2.describe_instances(
        InstanceIds=[instance_id]
    ) ['Reservations'][0]['Instances'][0]

2)instance不是对象,而只是包含'Tags'键的常规字典。

>>> instance['Tags']
[{'Key': 'Name', 'Value': 'instance-1'}]