ansible - 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 }}'
我想保持字典原样,如果可能的话,不要重建它以使用列表。
解决方案
我设法用include_tasks
and做到了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 }}'
推荐阅读
- docker - 厨房创建错误:无法完成#create 操作:[work_image build failed: The command '/bin/sh -c yum install -y hostname iproute less lsof
- javascript - 手动添加到 HTML 范围输入会产生意想不到的结果
- twilio - Twilio Studio 创建变量
- r - 在R中用匹配替换字符串的问题
- php - laravel 中的短信
- amazon-cloudformation - Cloudformation 模板中 Parameter Store 中 EC2 实例类型的动态参考
- php - 每天在服务器上保存文件副本
- google-chrome-extension - 获取 API、Chrome 扩展、内容脚本、CORS 权限
- angular - 在Angular 7中使用httpClient删除数组中的数组
- python - 使用概率标签训练 LSTM