如何将sql脚本输出的寄存器值转换为json对象

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

我是 ansible 的新手,我有一个 sal 文件,执行时给出的结果如下所示:

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'']"'

但我想要得到这样的东西

消息:

 - 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 }}"
json ansible
1个回答
0
投票

例如,给定文件

shell> cat test.txt 

zdf02ahg04.adf.corp.domain.com 
/home/eof/goto/tfe 

zdf03ahg04.adf.corp.domain.com 
/home/eof/goto4/tfe

阅读它

    - command: cat test.txt
      register: out
    - debug:
        var: out.stdout

给予

  out.stdout: |2-
  
    zdf02ahg04.adf.corp.domain.com
    /home/eof/goto/tfe
  
    zdf03ahg04.adf.corp.domain.com
    /home/eof/goto4/tfe

分割并选择非空行。使用过滤器batch并创建子列表。然后,使用过滤器 community.general.dict 并创建字典列表

  my_var: "{{ out.stdout | split('\n') | select | batch(2) |
              map('zip', ['HOSTNAME', 'Path']) |
              map('map', 'reverse') |
              map('community.general.dict') }}"

给你想要的东西

  my_var:
  - HOSTNAME: zdf02ahg04.adf.corp.domain.com
    Path: /home/eof/goto/tfe
  - HOSTNAME: zdf03ahg04.adf.corp.domain.com
    Path: /home/eof/goto4/tfe

用于测试的完整剧本示例

- hosts: localhost

  vars:

    my_var: "{{ out.stdout | split('\n') | select | batch(2) |
                map('zip', ['HOSTNAME', 'Path']) |
                map('map', 'reverse') |
                map('community.general.dict') }}"

  tasks:

    - command: cat test.txt
      register: out
    - debug:
        var: out.stdout

    - debug:
        var: my_var
© www.soinside.com 2019 - 2024. All rights reserved.