JMESPath在树中下降以进行过滤 [英] JMESPath descend in tree for filter

查看:61
本文介绍了JMESPath在树中下降以进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用describe-instances提取根块设备的卷ID.

I want to extract the volume ID for the root block device using describe-instances.

aws ec2 describe-instances --filters "Name=tag:Backup,Values=True" --query 'Reservations[].Instances[].{Name: Tags[?Key==`Name`].Value | [0], Id: InstanceId, Block: BlockDeviceMappings[?DeviceName==RootDeviceName].Ebs.VolumeId, Test: RootDeviceName}'

aws ec2 describe-instances --filters "Name=tag:Backup,Values=True" --query 'Reservations[].Instances[].{Name: Tags[?Key==`Name`].Value | [0], Id: InstanceId, Block: BlockDeviceMappings[?DeviceName==RootDeviceName].Ebs.VolumeId, Test: RootDeviceName}'

几件事:

  1. Ebs.VolumeId不是DeviceName的直接后代,它是BlockDeviceMappings的后代.
  2. RootDeviceName不是BlockDeviceMappings的后代.
  1. Ebs.VolumeId is not the direct descendant of DeviceName, it is descending from BlockDeviceMappings.
  2. RootDeviceName is not a descendant of BlockDeviceMappings.

因此,当我尝试拉RootDeviceName并相应地搜索VolumeId时,我得到一个空白字段(块:用于测试,与情况无关).

So when I'm trying to pull the RootDeviceName and search the VolumeId accordingly I'm getting a blank field (Block: is for testing and irrelevant to the case).

前2个字段正确.

提前谢谢!

推荐答案

是的,这是一个很大的问题!

Yes, that is quite an ask!

我最接近的工作是为DeviceName指定实际值:

The closest I got working was to specify the actual value for DeviceName:

aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId, BlockDeviceMappings[?DeviceName==`/dev/xvda`].Ebs.VolumeId]'

(此语法在Mac上有效.)

(This syntax worked on a Mac.)

坦率地说,我建议使用一种语言进行调用(例如Python),然后应用您自己的逻辑,而不是试图说服JMESPath提取正确的值.

Frankly, I'd recommend using a language to make the call (eg Python) and then apply your own logic, rather than trying to convince JMESPath to extract the correct values.

会是这样的:

import boto3

ec2_client = boto3.client('ec2', region_name = 'ap-southeast-2')

response = ec2_client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Backup',
            'Values': ['True']
        }
    ]
)

for r in response['Reservations']:
    for i in r['Instances']:
        name = [t['Value'] for t in i['Tags'] if t['Key'] == 'Name'][0]
        for b in i['BlockDeviceMappings']:
            if b['DeviceName'] == i['RootDeviceName']:
                print (i['InstanceId'], name, b['Ebs']['VolumeId'])

这篇关于JMESPath在树中下降以进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆