Reputation: 11
The issue that I am having is that the output.txt file keeps getting overwritten when I have multiple hosts. Is there something that I am missing so that I can have information from multiple hosts saved in the same .txt file? This is the playbook that I am currently running.
hosts: ROUTERS
gather_facts: false
connection: network_cli
tasks:
-name: Cellular_hardware
ios_command:
commands:
- sh run | i hostname
- sh cellular 0/2/0 hardware | i Modem Firmware|PRI
register: output
- name: copy output to file
debug:
var: output
- name: copy output to file
copy:
content: "{{ output.stdout_lines }}('\n')"
dest: "output.txt"
Upvotes: 1
Views: 2437
Reputation: 68404
To create one file at the controller with the output from all hosts use template and delegate the task to localhost. Run it once. For example
- name: copy output to file
template:
src: output.txt.j2
dest: output.txt
delegate_to: localhost
run_once: true
shell> cat output.txt.j2
{% for host in ansible_play_hosts_all %}
{{ host }}
{{ hostvars[host]['output']['stdout_lines'] }}
{% endfor %}
(not tested)
Fit the template to your needs.
The strategies can influence the availability of the variables. See ansible_play_hosts_all vs. ansible_play_batch. It is a good idea to split the playbook to 2 plays. Collect the output of all hosts in the first play and write the file in the second play. For example
shell> cat playbook.yml
- name: Collect output
hosts: ROUTERS
gather_facts: false
connection: network_cli
tasks:
- name: Cellular_hardware
ios_command:
commands:
- sh run | i hostname
- sh cellular 0/2/0 hardware | i Modem Firmware|PRI
register: output
- name: Debug output
debug:
var: output
- name: Write output to file
hosts: ROUTERS
gather_facts: false
connection: network_cli
tasks:
- name: copy output to file
template:
src: output.txt.j2
dest: output.txt
delegate_to: localhost
run_once: true
(not tested)
Upvotes: 3
Reputation: 1864
I you can use lineinfile module and append a record to the file, I have used lineinfile, it worked for me to get output in the file based on audit records.
- name: Add a line to a file.
lineinfile:
path: /tmp/output.txt
line: "{{ output.stdout_lines }}"
create: yes
delegate_to: localhost
Upvotes: 0