5

with_subelements用来循环一些嵌套数据。我想循环嵌套元素,但在迭代时对第二级数据进行排序。

    - 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

我尝试了一些方法来对列表进行排序,但我怀疑我正在使用with_subelements是否以应该使用的方式使用它。

我试过这个没有成功:

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

with_sorted_subelements如果不编写我自己的插件,这可能吗?

4

1 回答 1

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"
于 2017-10-30T19:53:29.417 回答