JMESPath在树中下降以进行过滤 [英] JMESPath descend in tree for filter
问题描述
我想使用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}'
几件事:
-
Ebs.VolumeId
不是DeviceName
的直接后代,它是BlockDeviceMappings
的后代. -
RootDeviceName
不是BlockDeviceMappings
的后代.
Ebs.VolumeId
is not the direct descendant ofDeviceName
, it is descending fromBlockDeviceMappings
.RootDeviceName
is not a descendant ofBlockDeviceMappings
.
因此,当我尝试拉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屋!