Ansible:结合主字典键与子字典列表元素生成报告
问题:Ansible 嵌套字典数据的格式化报告生成
我有一个主字典,其中每个元素都包含一个字典列表,希望生成一份包含主字典的键以及每个子字典子元素的报告。
数据结构
vars: array_info: purefa_info: hosts: devhost: volumes: - {hostgroup: null, lun: 10, volume: 'vol_0'} - {hostgroup: null, lun: 11, volume: 'vol_1'} prdhost: volumes: - {hostgroup: prodhosts, lun: 12, volume: vol_2} - {hostgroup: prodhosts, lun: 13, volume: vol_3}
期望输出格式
devhost,vol_0,10, devhost,vol_1,11, prdhost,vol_2,12,prodhosts prdhost,vol_3,13,prodhosts
当前尝试的任务代码
--- - name: recurse and report dicts hosts: all connection: local gather_facts: false vars: array_info: purefa_info: hosts: devhost: volumes: - {hostgroup: null, lun: 10, volume: 'vol_0'} - {hostgroup: null, lun: 11, volume: 'vol_1'} prdhost: volumes: - {hostgroup: prodhosts, lun: 12, volume: vol_2} - {hostgroup: prodhosts, lun: 13, volume: vol_3} tasks: - name: 获取字典键,但volumes是字典列表 debug: msg: "{{ item.key, item.value['volumes'] }}" with_dict: "{{ array_info.purefa_info.hosts }}" - name: 获取子元素,但拿不到主字典的键 ansible.builtin.debug: msg: "{{ item.1.volume }},{{ item.1.lun }},{{ item.1.hostgroup }}" with_subelements: - "{{ array_info.purefa_info.hosts }}" - volumes
解决方案
可以通过dict2items将主字典转换为键值对列表,再嵌套循环每个主机的卷列表,同时处理null值为空字符串的情况:
- name: 生成目标格式的报告内容 debug: msg: "{{ item.key }},{{ vol.volume }},{{ vol.lun }},{{ vol.hostgroup | default('') }}" loop: "{{ array_info.purefa_info.hosts | dict2items }}" loop_control: loop_var: item vars: vols: "{{ item.value.volumes }}" with_items: "{{ vols }}" loop_control: loop_var: vol
如果需要将结果保存到文件,可以结合copy模块和Jinja2模板:
- 先构造完整的报告内容列表:
- name: 构造报告内容列表 set_fact: report_lines: "{{ report_lines | default([]) + [item.key ~ ',' ~ vol.volume ~ ',' ~ vol.lun ~ ',' ~ (vol.hostgroup | default(''))] }}" loop: "{{ array_info.purefa_info.hosts | dict2items }}" loop_control: loop_var: item vars: vols: "{{ item.value.volumes }}" with_items: "{{ vols }}" loop_control: loop_var: vol
- 将列表写入文件:
- name: 写入报告文件 copy: content: "{{ report_lines | join('\n') }}" dest: ./volume_report.txt
这样就能生成符合期望格式的报告,同时处理hostgroup为null时输出空字符串的场景。
内容的提问来源于stack exchange,提问作者sambo4.0r13
相关产品推荐
相关产品推荐

