Ansible 执行多个命令并将输出保存到文件

178次阅读
没有评论

问题描述

在使用 Ansible 脚本时,希望执行多个命令并将它们的输出保存到文件。然而,目前只能获取到第一个命令的输出。用户有200个 VRF(虚拟路由转发),不知道是否需要为每个命令编写多个任务,还是有其他解决方案可以实现这个需求。

以下是用户的 Ansible 脚本示例:

---
name: PING_TenGig_Ethernet_VRFs
hosts: fr1.s05
gather_facts: false
connection: local
tasks:
  - name: run multiple commands on remote nodes
    ios_command:
      commands:
        - show bgp vrf Mgmt-intf
        - show bgp vrf cha-00 all summary
        - show bgp vrf cha-001 all summary
        - show bgp vrf cha-002 all summary
        - show bgp vrf cha-00303 all summary
    register: print_output
  - debug: var=print_output.stdout_lines
  - name: save output to a file
    copy: content="{{ print_output.stdout[0] }}" dest="./output/{{ inventory_hostname }}.txt"

解决方案

请注意以下操作可能因 Ansible 版本不同而有所差异。
要解决这个问题,你需要将多个命令的输出逐个保存到文件中。同时,还可以改进输出的格式以便更好地阅读。

步骤1:保存多个命令的输出

使用 register 关键字将多个命令的输出保存在变量中,然后逐个将这些输出保存到文件。

run multiple commands on remote nodes 任务之后,添加以下任务来保存多个命令的输出:

  - name: save output to a file
    copy: content="{{ item }}" dest="./output/{{ inventory_hostname }}.txt"
    loop: "{{ print_output.stdout }}"

这个任务会使用循环逐个处理 print_output.stdout 中的每个输出,并将其保存到文件中。这样就能够保留所有命令的输出。

步骤2:改进输出格式

如果输出的水平行格式难以阅读,你可以尝试将输出格式改为更易读的形式。可以使用 Ansible 提供的 lineinfile 模块来实现。

save output to a file 任务之后,添加以下任务来改进输出格式:

  - name: improve output format
    lineinfile:
      create: yes
      line: "{{ item }}"
      path: "./output/{{ inventory_hostname }}.txt"
    loop: "{{ print_output.stdout }}"

这个任务会逐行读取 print_output.stdout 中的每个输出,并将其按行添加到文件中。这样输出就会更加易读。

完整的 Ansible 脚本示例

以下是完整的 Ansible 脚本示例,包括上述步骤:

---
name: PING_TenGig_Ethernet_VRFs
hosts: fr1.s05
gather_facts: false
connection: local
tasks:
  - name: run multiple commands on remote nodes
    ios_command:
      commands:
        - show bgp vrf Mgmt-intf
        - show bgp vrf cha-00 all summary
        - show bgp vrf cha-001 all summary
        - show bgp vrf cha-002 all summary
        - show bgp vrf cha-00303 all summary
    register: print_output
  - debug: var=print_output.stdout_lines
  - name: save output to a file
    copy: content="{{ item }}" dest="./output/{{ inventory_hostname }}.txt"
    loop: "{{ print_output.stdout }}"
  - name: improve output format
    lineinfile:
      create: yes
      line: "{{ item }}"
      path: "./output/{{ inventory_hostname }}.txt"
    loop: "{{ print_output.stdout }}"

结论

通过将多个命令的输出保存到文件并改进输出格式,你可以在 Ansible 脚本中实现执行多个命令并将输出保存到文件的需求。这样可以更好地组织和查阅命令的输出信息。

正文完