首页 > 解决方案 > Ansible - 遍历嵌套字典(没有列表)

问题描述

我找到了很多关于如何循环嵌套 Ansible 字典的答案,但每个都包含带有命名项的列表。我有一本没有列表的字典:

xml_files:
  file1:
    key1:
      attr1: value1
      attr2: value2
    key2:
      attr1: value1
  file2:
    key1:
      attr1: value1

此外,键(key1, key2)、属性(attr1, attr2)和它们的值(value1, value2)是动态的,它们可以通过combine过滤器使用从命令行发送的值来添加/更新。只有文件名(file1, file2)是已知的。

现在,我想更新每个文件中由固定 xpath 指定的元素中每个属性的值。

我为每个文件尝试了一项任务,with_dict但我不知道如何获取属性名称和值。我还需要为每个属性运行任务。

- name: update XML values in file1
  xml:
    path: '/path/to/file1/{{ item.key }}'
    xpath: '/some/xpath'
    attribute: '{{ ??? }}'
    value: '{{ ??? }}'
  with_dict: '{{ xml_files.file1 }}'

- name: update XML values in file2
  xml:
    path: '/path/to/file2/{{ item.key }}'
    xpath: '/different/xpath'
    attribute: '{{ ??? }}'
    value: '{{ ??? }}'
  with_dict: '{{ xml_files.file2 }}'

我想保持字典原样,如果可能的话,不要重建它以使用列表。

标签: ansible

解决方案


我设法用include_tasksand做到了loop_control。我仍然会寻找更好的解决方案。

xml_files:
  file1:
    key1:
      attr1: value1
      attr2: value2
  file2:
    key1:
      attr1: value1

my_task.yml
-----------

- include_tasks: set_xml.yml file='file1' xpath='/some/xpath'
  with_dict: '{{ xml_files.file1 }}'
  loop_control:
    loop_var: xml_keys

- include_tasks: set_xml.yml file='file2' xpath='/different/xpath'
  with_dict: '{{ xml_files.file2 }}'
  loop_control:
    loop_var: xml_keys

set_xml.yml
-----------

- name: update XML values in {{ file }}
  xml:
    path: '/path/to/file/{{ file }}.xml'
    xpath: '{{ xpath }}'
    attribute: '{{ item.key }}'
    value: '{{ item.value }}'
  with_dict: '{{ xml_keys.value }}'



推荐阅读