python - 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'])
先感谢您
解决方案
以下是代码,您可能需要更改逻辑以将数据附加到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)
推荐阅读
- amazon-web-services - S3 仅对一个 IAM 用户的访问
- excel - Excel IF 规则。如果应用于公式的单元格通过测试,我可以输入活单元格的值吗?
- logging - Airflow KubernetesExecutor,在执行程序 pod 完成之前,日志不会显示在 UI 中
- swift - 确定用户是否有资格通过 Mac App 上的本地收据验证免费试用的正确方法是什么?
- api - jAgent 是否支持 https 端点?
- git - 为什么在我做了'checkout master'之后,我在新分支中所做的更改会显示在master中?
- html - 为什么我的 H1 标题子级会覆盖我的 div 父级维度?为什么我不能正确操作 h1?
- html - 'type=url' 上的自定义验证消息
- c++ - nvJPEG:编码打包的 BGR
- iphone - iPhone 7 上的 Google Assistant 显示没有麦克风或键盘