Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible writing output from multiple task to a single file

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?

like image 402
user3059993 Avatar asked Jul 13 '16 23:07

user3059993


2 Answers

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.

like image 152
Amit Avatar answered Oct 19 '22 13:10

Amit


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 
like image 43
Dmitriy Avatar answered Oct 19 '22 11:10

Dmitriy