5

I am using with_subelements to loop over some nested data. I would like to loop over the nested elements but sort the second level of data when it is iterated over.

    - name: Can I haz sorted nested elements?
      debug: msg="device={{item.0.key}}, mounted at {{item.1.mount_point}}"
      when: profile_data.enabled
      with_subelements:
        - profile_data.layouts
        - partitions

I have tried a few things to sort the list, but I doubt I am using with_subelements in the way it is supposed to be used.

I tried this without success:

      with_subelements:
        - profile_data.layouts
        - "{{ partitions|sort(attribute='number') }}"

Is this possible without writing my own with_sorted_subelements plugin?

Randy
  • 908
  • 12
  • 30

1 Answers1

6

It depends on exactly what data from the structure you really need.

Here's an example of sorting nested elements:

---
- hosts: localhost
  gather_facts: no
  vars:
    mydict:
      key1:
        key: hello
        persons:
          - name: John
            age: 30
          - name: Mark
            age: 50
          - name: Peter
            age: 40
      key2:
        key: world
        persons:
          - name: Mary
            age: 30
          - name: Julia
            age: 25
          - name: Paola
            age: 35
  tasks:
    - debug:
        msg: "{{ item.0.k }} {{ item.1.age }} {{ item.1.name }}"
      with_subelements:
        - "{{ mydict | json_query('*.{k:key, p:sort_by(persons, &age)}') }}"
        - p

Here I take key as k and sorted persons as p from original dict, and feed it to with_subelements.

The output is:

"msg": "world 25 Julia"
"msg": "world 30 Mary"
"msg": "world 35 Paola"
"msg": "hello 30 John"
"msg": "hello 40 Peter"
"msg": "hello 50 Mark"
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • I didn't know about `json_query`, and it looks promising. Unfortunately I am stuck on Ansible 1.9.2 (and yes, I know about its flaws). – Randy Oct 30 '17 at 20:32