如何使用ANSIBLE将多个主机的多个stdout_lines保存到一个txt文件中?



我遇到的问题是,当我有多个主机时,输出.txt文件不断被覆盖。我是否缺少一些内容,以便我可以将来自多个主机的信息保存在同一个.txt文件中?这是我目前正在运行的剧本。

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"

要在控制器上创建一个文件,其中包含所有主机的输出,请使用模板并将任务委托给本地主机。运行一次。例如

- 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 %}

(未测试(

使模板适合您的需求。


这些策略可以影响变量的可用性。请参阅ansible_play_hosts_all与ansible_play_batch。最好将剧本分成 2 部剧本。在第一次播放中收集所有主机的输出,并在第二次播放中写入文件。例如

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

(未测试(

我可以使用lineinfile模块并将记录附加到文件中,我使用了lineinfile,它为我根据审计记录在文件中获取输出。

- name: Add a line to a file. lineinfile: path: /tmp/output.txt line: "{{ output.stdout_lines }}" create: yes delegate_to: localhost

相关内容

最新更新