Ansible - 将命令输出复制到多个主机的文件
Ansible - Copy command output to file for multiple hosts
我 运行 一个剧本,其中包含针对多个 Cisco Nexus 主机的单个命令。对于所有主机,我想将命令的输出存储在控制器上的单个文件中。
---
- name: Nxos
hosts:
- sw1
- sw2
gather_facts: false
tasks:
- name: interface counters
cisco.nxos.nxos_command:
commands: show interface counters errors non-zero
register: output
但是,使用下面的这种方法,只有 1 个主机的输出被保存,而其他的没有。
- name: copy output to file
copy: content="{{ output.stdout[0] }}" dest="output.txt"
然而,如果我使用以下方法,有时会为所有主机存储输出,而其他时候它只会为随机数量的主机存储输出
- name: Copy output to file
local_action:
module: lineinfile
path: output.txt
line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
create: yes
知道可能有什么问题或存储输出的最佳方式是什么吗?
谢谢
如果您总是写入名为 output.txt
的文件,那么您当然只会看到单个主机的输出——对于每个主机,Ansible re-writes 包含新数据的文件。没有魔法告诉 Ansible 它应该附加到文件或其他东西。
最简单的解决方案是将输出写入以每个主机命名的文件,如下所示:
- name: copy output to file
copy:
content: "{{ output.stdout[0] }}
dest: "output-{{ inventory_hostname }}.txt"
如果需要,您可以在剧本末尾添加一个任务
会将所有这些文件连接在一起。
使用 delegate_to: localhost
代替 local_action
并且 运行 任务仅一次。在content
中,迭代special variableansible_play_hosts_all
和select注册的输出hostvars
。例如下面的剧本
- hosts: sw1,sw2
gather_facts: false
tasks:
- command: "echo {{ inventory_hostname }}"
register: output
- name: Copy output to file
copy:
dest: output.txt
content: |-
{% for host in ansible_play_hosts_all %}
{{ '###' }}{{ host }}{{ '###' }}
{{ hostvars[host]['output']['stdout'] }}
{% endfor %}
delegate_to: localhost
run_once: true
给予
shell> cat output.txt
###sw1###
sw1
###sw2###
sw2
我 运行 一个剧本,其中包含针对多个 Cisco Nexus 主机的单个命令。对于所有主机,我想将命令的输出存储在控制器上的单个文件中。
---
- name: Nxos
hosts:
- sw1
- sw2
gather_facts: false
tasks:
- name: interface counters
cisco.nxos.nxos_command:
commands: show interface counters errors non-zero
register: output
但是,使用下面的这种方法,只有 1 个主机的输出被保存,而其他的没有。
- name: copy output to file
copy: content="{{ output.stdout[0] }}" dest="output.txt"
然而,如果我使用以下方法,有时会为所有主机存储输出,而其他时候它只会为随机数量的主机存储输出
- name: Copy output to file
local_action:
module: lineinfile
path: output.txt
line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
create: yes
知道可能有什么问题或存储输出的最佳方式是什么吗?
谢谢
如果您总是写入名为 output.txt
的文件,那么您当然只会看到单个主机的输出——对于每个主机,Ansible re-writes 包含新数据的文件。没有魔法告诉 Ansible 它应该附加到文件或其他东西。
最简单的解决方案是将输出写入以每个主机命名的文件,如下所示:
- name: copy output to file
copy:
content: "{{ output.stdout[0] }}
dest: "output-{{ inventory_hostname }}.txt"
如果需要,您可以在剧本末尾添加一个任务 会将所有这些文件连接在一起。
使用 delegate_to: localhost
代替 local_action
并且 运行 任务仅一次。在content
中,迭代special variableansible_play_hosts_all
和select注册的输出hostvars
。例如下面的剧本
- hosts: sw1,sw2
gather_facts: false
tasks:
- command: "echo {{ inventory_hostname }}"
register: output
- name: Copy output to file
copy:
dest: output.txt
content: |-
{% for host in ansible_play_hosts_all %}
{{ '###' }}{{ host }}{{ '###' }}
{{ hostvars[host]['output']['stdout'] }}
{% endfor %}
delegate_to: localhost
run_once: true
给予
shell> cat output.txt
###sw1###
sw1
###sw2###
sw2