Python3-从json解析AWS实例标签。发生错误行为

问题描述 投票:2回答:1

我的任务:解析“ aws ec2 describe-instances” json输出的输出,以收集各种实例详细信息,包括分配给该实例的“名称”标签。

我的代码摘录:

# Query AWS ec2 for instance information
        my_aws_instances = subprocess.check_output("/home/XXXXX/.local/bin/aws ec2 describe-instances --region %s --profile %s" % (region, current_profile), shell=True)

        # Convert AWS json to python dictionary
        my_instance_dict = json.loads(my_aws_instances)

        # Pre-enter the 'Reservations' top level dictionary to make 'if' statement below cleaner.
        my_instances = my_instance_dict['Reservations']

        if my_instances:

            for my_instance in my_instances:

                if 'PublicIpAddress' in my_instance['Instances'][0]:
                    public_ip = my_instance['Instances'][0]['PublicIpAddress']
                else:
                    public_ip = "None"

                if 'PrivateIpAddress' in my_instance['Instances'][0]:
                    private_ip = my_instance['Instances'][0]['PrivateIpAddress']
                else:
                    private_ip = "None"

                if 'Tags' in my_instance['Instances'][0]:
                    tag_list = my_instance['Instances'][0]['Tags']

                    for tag in tag_list:
                        my_tag = tag.get('Key')

                        if my_tag == "Name":
                            instance_name = tag.get('Value')
                        else:
                            instance_name = "None"

                state         = my_instance['Instances'][0]['State']['Name']
                instance_id   = my_instance['Instances'][0]['InstanceId']
                instance_type = my_instance['Instances'][0]['InstanceType']

这是“ tag”变量在循环中包含的内容的示例。这是python字典:

{'Value': 'server_name01.domain.com', 'Key': 'Name'}

如果有帮助,这是实例标签的原始json:

 "Tags": [
                        {
                            "Value": "migration test",
                            "Key": "Name"
                        }
                    ],

除了“标记”部分外,其他所有东西都起作用,即使在所有情况下都存在我正在测试的“名称”值,“标记”部分在某些情况下也不会起作用。换句话说,在某些确实具有“名称”标签和名称的实例上,结果是“无”。我已经排除了服务器名称本身的问题,即空格和特殊字符与结果混淆。我还尝试确保python正在查找“名称”,并且没有其他变体。在这一点上我很困惑,任何帮助将不胜感激。

提前感谢

python json amazon-web-services parsing tags
1个回答
0
投票
for tag in tag_list: my_tag = tag.get('Key') if my_tag == "Name": instance_name = tag.get('Value') else: instance_name = "None"

假设您有一个带有两个标签的实例,

[
  {
    "Key": "Name",
    "Value": "My_Name"
  },
  {
    "Key": "foo",
    "Value": "bar"
  }
]

[遍历for循环时,它将首先评估Name: My_Name键-值对并将instance_name设置为My_Name,但是for循环将继续运行,并评估第二个键-值对。它将instance_name设置为None,覆盖先前分配的值。

一种简单的解决方案是找到Name键后退出for循环,例如:

for tag in tag_list: my_tag = tag.get('Key') if my_tag == "Name": instance_name = tag.get('Value') break else: instance_name = "None"

© www.soinside.com 2019 - 2024. All rights reserved.