3

Is there an easy way to log output from multiple remote hosts to a single file on the server running ansible-playbook?

I have a variable called validate which stores the output of a command executed on each server. I want to take validate.stdout_lines and drop the lines from each host into one file locally.

Here is one of the snippets I wrote but did not work:

- name: Write results to logfile
  blockinfile:
    create: yes
    path: "/var/log/ansible/log"
    insertafter: BOF
    block: "{{ validate.stdout }}"
  delegate_to: localhost

When I executed my playbook w/ the above, it was only able to capture the output from one of the remote hosts. I want to capture the lines from all hosts in that single /var/log/ansible/log file.

techraf
  • 64,883
  • 27
  • 193
  • 198

1 Answers1

2

One thing you should do is to add a marker to the blockinfile to wrap the result from each single host in a unique block.

The second problem is that the tasks would run in parallel (even with delegate_to: localhost, because the loop here is realised by the Ansible engine) with effectively one task overwriting the other's /var/log/ansible/log file.

As a quick workaround you can serialise the whole play:

- hosts: ...
  serial: 1

  tasks:
    - name: Write results to logfile
      blockinfile:
        create: yes
        path: "/var/log/ansible/log"
        insertafter: BOF
        block: "{{ validate.stdout }}"
        marker: "# {{ inventory_hostname }} {mark}"
      delegate_to: localhost

The above produces the intended result, but if serial execution is a problem, you might consider writing your own loop for this single task (for ideas refer to support for "serial" on an individual task #12170).


Speaking of other methods, in two tasks: you can concatenate the results into a single list (no issue with parallel execution then, but pay attention to delegated facts) and then write to a file using copy module (see Write variable to a file in Ansible).

techraf
  • 64,883
  • 27
  • 193
  • 198
  • Thanks techraf! Using your references I was able to devise a solution, which I appended to your response. –  Sep 18 '17 at 16:57