I’m parsing some values using json_query
. After extracting the values I’m left with a list of elements which contain the list of values. My goal is to have a single list of un-nested values.
How can I achieve this?
E.g.:
my_list: [ [1,2],[3,4],[5,6] ]
Should become
my_list: [1,2,3,4,5,6]
I can’t use my_list[0] | union([my_list[1]) | union(my_list[2])
because the my_list is dynamic.
2
Answers
You can use a custom plugin to handle Python-like jobs easily. To do this, create a folder named filter_plugins (make sure to use this reserved name) in the same folder as your playbook, and add your Python filter there.
Make sure the filter contains the FilterModule class and filters method:
Call the new filter from your Ansible playbook:
Here is the inventory file, just for reference and to complete the example:
And here is the result of the execution:
Use the
flatten
filter.Given:
This yields the expected list:
And since you state that you are using
json_query
, note that there is also a way to flatten in JMESPath, called flatten projection, so you might bake this is your existing query.As an example:
Will also yield the expected result.