Question:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
--- - 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:
You can try something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
- 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.