Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Parent Element in JMESPath Filter Expression

I have the following JMESPath query

query="Reservations[].Instances[].{ \
    InstanceId: InstanceId, \
    RootDeviceVolumeId: BlockDeviceMappings[?DeviceName==\`/dev/sda1\`] \
       | [].Ebs.VolumeId | [0], \
    RootDeviceName: RootDeviceName \
}"

aws ec2 describe-instances --query $query

which gives output like this

InstanceId RootDeviceName RootDeviceVolumeId
i-12345678 /dev/sda1 vol-abcdef12
i-98765432 /dev/sda1 vol-ef123456
i-23456789 /dev/sda1 vol-fedcba09
i-aabbccdd /dev/xvda None

I'd like to find a way to reference the RootDeviceName from within the BlockDeviceMappings filter expression rather than hard-coding the /dev/sda1 device name, since sometimes it's /dev/xvda for instance. However, I can't find a way to reference a parent element in the filter expression.

Another option would be to map the RootDeviceName and InstanceId onto a projection of all devices and then pipe that to a filter expression, but the syntax doesn't seem to support including parent elements in projections either.

Am I missing something or is this simply a limitation of the JMESPath syntax?

like image 896
Joe Taylor Avatar asked Jun 21 '26 13:06

Joe Taylor


2 Answers

We would need to have some mechanism that allows you to bind scope, which is something that is not currently possible... yet. I'm very interested in adding this. For now you'll have to use an alternate tool.

like image 72
jamesls Avatar answered Jun 24 '26 19:06

jamesls


If you're willing to add custom functions to your JMESPath-using python code, there is a dirty and ugly way that does something like it. It does violate the "functions should have no side effects" rule. Here's the gist: https://gist.github.com/martinvirtel/366235401cf7fbec503d53eb44109f25

The fetchstore.py file in the gist adds a fetch and a store function to JMESPath. See the test or the example below for how it works. Here is guidance on how to add functions to your JMESPath-using Python project: https://pypi.python.org/pypi/jmespath#custom-functions.

Input:

 { "name" : "parent name",
    "data" : [
        { "x" : 1, "y" : 2 },
        { "x" : 3, "y" : 2 }
        ]
    }

JMESPath Expression:

{ 
  name: store(name,'parent_name_attribute'), 
  data: data[][ fetch('parent_name_attribute'),x, y] 
}

Result:

{
 "name": "parent name",
 "data": [
           [ "parent name", 1, 2 ],
           [ "parent name", 3, 2 ]
         ]
}
like image 31
mvtango Avatar answered Jun 24 '26 20:06

mvtango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!