按键对嵌套的Ansible字典进行排序

时间:2020-04-27 15:13:41

标签: python ansible

我们有一个艰巨的任务

- name: Migrate Zookeeper settings
  zoo_import:
    version: "{{ item[0] }}"
    content: "{{ item[1] }}"
  with_items: "{{ zk_import | dictsort }}"

zoo_import 模块期望字符串 version 和字典 content ,而我猜 dictsort 会生成元组列表。

那么如何将列表项传递给模块?最明显的变体内容:{{dict(item [1])}}结尾于“字典更新序列元素#0的长度为1;要求为2”

谢谢。

PS如果很重要,则排序前的zk_import词典就像

zk_import:
  v20200420:
    to_update:
      '/path1/key1/': 'value2'
      '/path2/key1/': 'other value'
    to_delete:
      '/path/key/': 'value2'
      '/path/key1/subkey': 'other value'
  v20200425:
      etc...

1 个答案:

答案 0 :(得分:2)

在Ansible> = 2.5中,您应该使用loop而不是with_items

loop: "{{ zk_import | dictsort }}"

在Ansible <= 2.4中,您需要使用:

with_items:
  - "{{ zk_import | dictsort }}"

这是with_items的一种特殊行为,即documented

请注意,with_items使提供的列表的第一深度变平,如果传递由列表组成的列表,则可能会产生意外的结果。您可以通过将嵌套列表包装在列表中来解决此问题:

# This will run debug once with the three items
- debug:
    msg: "{{ item }}"   vars:
    nested_list:
      - - one
        - two
        - three   with_items:
    - "{{ nested_list }}"