9

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?

user3059993
  • 324
  • 1
  • 4
  • 9

3 Answers3

11

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.

Amit
  • 1,006
  • 1
  • 7
  • 13
3

Ansible doc recommend use copy:

- name: get jstack                                                                        
  shell: "/usr/lib/jvm/java/bin/jstack -l {{PID_JAVA_APP}}"                                                             
  args:                                                                                                      
    executable: /bin/bash
  register: jstackOut                                           

- name: write jstack                                                                                
  copy:                                                                                              
     content: "{{jstackOut.stdout}}" 
     dest: "tmp/jstack.txt"

If you want write local file, add this:

     delegate_to: localhost 
Dmitriy
  • 47
  • 2
  • 4
    This is useless when output is multiline. Line is always overwritten by new line. – QkiZ Nov 24 '17 at 11:26
0

Why to complicate things ?

I did this like that and it worked:

ansible-playbook your_playbook.yml >> /file/you/want/to/redirect/output.txt

you can also try some parsing with grep or some other stuff with tee -a.

Irka Irenka
  • 164
  • 10
  • The issue with this solution is that in cannot be applied to a playbook launched by AWX or Tower. – Lou May 25 '22 at 12:19