如何将SQL脚本输出的注册值转换为指定结构的JSON对象?Ansible求助
Ansible结构化SQL输出结果处理
原始输出
执行SQL文件后得到如下格式的输出:
Msg: |- zdf02ahg04.adf.corp.domain.com /home/eof/goto/tfe zdf03ahg04.adf.corp.domain.com /home/eof/goto4/tfe
当前处理结果
尝试将值传入to_json过滤器后,得到的结果如下:
msg: |- '"[''zdf02ahg04.adf.corp.domain.com'', ''/home/eof/goto/tfe'', '''', ''zdf03ahg04.adf.corp.domain.com'', ''/home/eof/goto4/tfe'']"'
期望结果
需要得到如下结构化格式的结果:
msg: - HOSTNAME: zdf02ahg04.adf.corp.domain.com Path: /home/eof/goto/tfe - HOSTNAME: zdf03ahg04.adf.corp.domain.com Path: /home/eof/goto4/tfe
已尝试代码
- set_fact: my_var: "{{ sql.stdout_lines | to_json }}" - debug: msg: "{{ my_var }}"
解决方案
核心思路是先过滤空行,再按每两个元素分组,最后映射为指定键的字典。
方法一(使用community.general集合)
- name: 转换SQL输出为结构化数据 set_fact: structured_hosts: > {{ sql.stdout_lines | reject('equalto', '') | batch(2) | map('community.general.dict', ['HOSTNAME', 'Path']) | list }} - name: 输出结构化结果 debug: var: structured_hosts
方法二(无需额外集合)
如果未安装community.general集合,可使用原生过滤器实现:
- name: 转换SQL输出为结构化数据 set_fact: structured_hosts: > {{ sql.stdout_lines | reject('equalto', '') | batch(2) | map('zip', ['HOSTNAME', 'Path']) | map('dict') | list }} - name: 输出结构化结果 debug: var: structured_hosts
说明
reject('equalto', ''):移除stdout_lines中的空字符串(对应原始输出里的空行)batch(2):将过滤后的列表按每2个元素为一组拆分map('community.general.dict', ['HOSTNAME', 'Path'])/map('zip', ...)|map('dict'):将每组元素映射为包含指定键的字典
内容的提问来源于stack exchange,提问作者Yashwanth Veeranki
相关产品推荐
相关产品推荐

