Ansible writing output from multiple task to a single file

user3059993 picture user3059993 · Jul 14, 2016 · Viewed 32.4k times · Source

In Ansible, I have written an Yaml playbook that takes list of host name and the executes command for each host. I have registered a variable for these task and at the end of executing a task I append output of each command to a single file. But every time I try to append to my output file, only the last record is getting persisted.

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

I even tried to append using lineinfile using insertafter parameter yet was not successful. Anything that I am missing?

Answer

Amit picture Amit · Jul 14, 2016

You can try something like this:

- 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

I have used serial: 1 as I am not sure if lineinfile tasks running in parallel will garble the output file.