繁体   English   中英

Python boto3 (AWS EC2) 列表嵌套 JSON 数据

[英]Python boto3 (AWS EC2) list Nested JSON Data

我使用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": [将所有值和 output 全部转换为一个字符串

我的代码

#!/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'])

先感谢您

以下是代码,您可能需要将逻辑更改为 append 数据到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)


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM