Reference Parent Element in JMESPath Filter Expression
Asked Answered
H

2

7

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?

Homogenize answered 23/2, 2015 at 12:23 Comment(0)
R
6

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.

Ravin answered 23/2, 2015 at 18:59 Comment(2)
Thanks for clarifying that. Are there any proposals around changes to this part the spec yet?Homogenize
@Ravin is this still the case now in 2018?Spruill
B
3

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 ]
         ]
}
Beera answered 7/11, 2017 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.