Ansible 将多个任务的输出写入单个文件

use*_*993 7 ansible-playbook ansible-2.x

在 Ansible 中,我编写了一个 Yaml 剧本,其中包含主机名列表和每个主机的执行命令。我已经为这些任务注册了一个变量,并在执行任务结束时将每个命令的输出附加到一个文件中。但是每次我尝试附加到我的输出文件时,只有最后一条记录被持久化。

---
- hosts: list_of_hosts
  become_user: some user
  vars:
    output: []
  tasks:
    - name: some name
      command: some command
      register: output
      failed_when: "'FAILED' in output"
    - debug: msg="{{output | to_nice_json}}"
    - local_action: copy content='{{output | to_nice_json}}' dest="/path/to/my/local/file"
Run Code Online (Sandbox Code Playgroud)

我什至尝试使用 insertafter 参数使用 lineinfile 进行追加,但没有成功。有什么我想念的吗?

Ami*_*mit 10

你可以尝试这样的事情:

- name: dummy
  hosts: myhosts
  serial: 1
  tasks:
    - name: create file
      file:
        dest: /tmp/foo
        state: touch
      delegate_to: localhost

    - name: run cmd
      shell: echo "{{ inventory_hostname }}"
      register: op

    - name: append
      lineinfile:
        dest: /tmp/foo
        line: "{{ op }}"
        insertafter: EOF
      delegate_to: localhost
Run Code Online (Sandbox Code Playgroud)

我使用过,serial: 1因为我不确定lineinfile并行运行的任务是否会导致输出文件出现乱码。