问题描述
我在Ansible配置中有一个字典列表
I have an list of dictionary in Ansible config
myList
- name: Bob
age: 25
- name: Alice
age: 18
address: USA
我写代码为
- name: loop through
debug: msg ="{{item.key}}:{{item.value}}"
with_items: "{{ myList }}"
我想打印出来
msg: "name:Bob age:25 name:Alice age:18 address:USA"
如何遍历该词典并获取键和值对?因为它不知道关键是什么.如果我将其更改为{{item.name}},则ansible可以使用,但我也想知道密钥
How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key
推荐答案
如果要遍历列表并分别解析每个项目,则:
If you want to loop through the list and parse every item separately:
- debug: msg="{{ item | dictsort | map('join',':') | join(' ') }}"
with_items: "{{ myList }}"
将打印:
"msg": "age:25 name:Bob"
"msg": "address:USA age:18 name:Alice"
如果您想将所有内容合并为一行,请使用:
If you want to join everything into one line, use:
- debug: msg="{{ myList | map('dictsort') | sum(start=[]) | map('join',':') | join(' ') }}"
这将给出:
"msg": "age:25 name:Bob address:USA age:18 name:Alice"
请记住,字典不是在Python中排序的,因此通常不能期望项目的顺序与yaml文件中的顺序相同.在我的示例中,它们在dictsort过滤器之后按键名排序.
Keep in mind that dicts are not sorted in Python, so you generally can't expect your items to be in the same order as in yaml-file. In my example, they are sorted by key name after dictsort filter.
这篇关于如何遍历字典列表,并在Ansible中打印出每个键和值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!