按键排序嵌套的Ansible字典

问题描述 投票:0回答:1

我们有这样艰巨的任务

- 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...
python ansible
1个回答
1
投票

在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 }}"
© www.soinside.com 2019 - 2024. All rights reserved.