以正确的 JSON 格式将 ansible 任务的输出写入文件

Write output of ansible task to file in proper JSON format

我正在尝试将 shell 任务输出写入 json,但我无法在有效的 json 文件中解析它。

这是 shell 任务输出的示例: {"firstname": "John", "lastname": "Smith", "user": "john"}

- name: 'Execute script'
  shell: /tmp/script.sh
  register: script_output

- name: 'Output to json'
  local_action:
    module: lineinfile
    dest: output.json
    line: '{{ script_output.stdout }}'
    create: yes

剧本执行后,json 文件具有以下内容:

{"firstname": "John", "lastname": "Smith", "user": "john"}
{"firstname": "John", "lastname": "Smith", "user": "john"}
{"firstname": "John", "lastname": "Smith", "user": "john"}

如何将输出格式化为附件中的 json 有效格式?

[
    {"firstname": "John", "lastname": "Smith", "user": "john"},
    {"firstname": "John", "lastname": "Smith", "user": "john"},
    {"firstname": "John", "lastname": "Smith", "user": "john"}
]

没有可执行此操作的 json module。但是您可以为此使用 third-party 模块,例如 ansible-jsonpatch

这是一个简单的案例,您可以使用@JGK 回复的内容,或者您​​可以只定义一个列表并向其中添加那些 json 元素。没有任何模块!

即:

  - vars:
      elem:
      - {"firstname": "John", "lastname": "Smith", "user": "john"}
      - {"firstname": "John", "lastname": "Smith", "user": "john"}
      - {"firstname": "John", "lastname": "Smith", "user": "john"}

  - set_fact:
      my_list: []

  - name: add to list
    set_fact:
      my_list: "{{ my_list + [item] }}"
    loop: "{{ elem }}"

  - debug:
      msg: "{{ my_list }}"

  - copy:
      content: "{{ my_list }}"
      dest: ./x.json
    delegate_to: localhost

这是使用 json python 模块或 jq 验证的结果:

$ jq . x.json
[
  {
    "lastname": "Smith",
    "user": "john",
    "firstname": "John"
  },
  {
    "lastname": "Smith",
    "user": "john",
    "firstname": "John"
  },
  {
    "lastname": "Smith",
    "user": "john",
    "firstname": "John"
  }
]

Python:

$ python -m json.tool x.json 
[
    {
        "firstname": "John",
        "lastname": "Smith",
        "user": "john"
    },
    {
        "firstname": "John",
        "lastname": "Smith",
        "user": "john"
    },
    {
        "firstname": "John",
        "lastname": "Smith",
        "user": "john"
    }
]