且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何遍历字典列表,并在Ansible中打印出每个键和值对

更新时间:2023-08-26 13:21:16

如果要遍历列表并分别解析每个项目,则:

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.