如何从 Ansible with_subelements 列表中排序项目
How to Sort Items from an Ansible with_subelements list
我正在使用 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
插件?
这取决于您真正需要的结构中的哪些数据。
下面是对嵌套元素进行排序的示例:
---
- 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
这里我把key
当成k
,然后从原始字典中把persons
当成p
排序,然后输入到with_subelements
.
输出为:
"msg": "world 25 Julia"
"msg": "world 30 Mary"
"msg": "world 35 Paola"
"msg": "hello 30 John"
"msg": "hello 40 Peter"
"msg": "hello 50 Mark"
我正在使用 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
插件?
这取决于您真正需要的结构中的哪些数据。
下面是对嵌套元素进行排序的示例:
---
- 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
这里我把key
当成k
,然后从原始字典中把persons
当成p
排序,然后输入到with_subelements
.
输出为:
"msg": "world 25 Julia"
"msg": "world 30 Mary"
"msg": "world 35 Paola"
"msg": "hello 30 John"
"msg": "hello 40 Peter"
"msg": "hello 50 Mark"