首页 > 解决方案 > Python boto3 (AWS EC2) 列出嵌套 JSON 数据

问题描述

我使用boto3来获取这样的所有实例的列表。

id: i-fa512784, zone: us-east-1, state: running, name: redis, env: staging-db, app: php
id: i-fa112784, zone: us-east-1, state: running, name: redis, env: production, app: php

我想为每个实例的所有值创建一个字符串。即每个实例都应该有自己的字符串和自己的键。我的目标是将这些数据放入 Prometheus。

我一直在解析嵌套"Tags": [以获取所有值并将它们全部输出到一个字符串中

我的代码

#!/usr/bin/python3

import boto3.utils
boto3.setup_default_session(profile_name='profile')
client = boto3.client('ec2')

response = client.describe_instances(
   MaxResults=10,
)

for r in response['Reservations']:
    for i in r['Instances']:
        for tags in i['Tags']:
        print ('id:',i['InstanceId'], 'zone:',i['Placement']['AvailabilityZone'], 'state:',i['State']['Name'])

先感谢您

标签: pythonamazon-web-servicesboto3

解决方案


以下是代码,您可能需要更改逻辑以将数据附加到tag_values_list;

#!/usr/bin/python3

import boto3.utils

boto3.setup_default_session(profile_name='profile')
client = boto3.client('ec2')

response = client.describe_instances(
    MaxResults=10,
)

for r in response['Reservations']:
    for i in r['Instances']:
        tag_values_list = []
        for tags in i['Tags']:
            for key, value in tags.items():
                tag_values_list.append(value)

        print('id:', i['InstanceId'], 'zone:', i['Placement']['AvailabilityZone'], 'state:', i['State']['Name'],
              'tags:',
              tag_values_list)



推荐阅读