在汇总文件里加上分隔符,每个主机的结果之间用一条横线区分,方便阅读。
优化后的 Playbook
保存为 ping_baidu.yml
:
- hosts: webservers
become: no
tasks:
- name: Ping www.baidu.com from each host
shell: ping -c 4 www.baidu.com
register: ping_result
- name: Collect results
set_fact:
ping_summary: "{{ ping_summary | default([]) + ['===== ' + inventory_hostname + ' =====\n' + ping_result.stdout] }}"
- hosts: localhost
gather_facts: no
tasks:
- name: Ensure result directory exists
file:
path: /tmp/ping_results
state: directory
mode: '0755'
- name: Save all results into one file
copy:
content: "{{ hostvars | dict2items | selectattr('value.ping_summary','defined') | map(attribute='value.ping_summary') | sum(start=[]) | join('\n\n') }}"
dest: /tmp/ping_results/all.log
执行
ansible-playbook -i /etc/ansible/hosts/inventory.ini ping_baidu.yml
结果文件 /tmp/ping_results/all.log
内容示例:
===== 10.0.19.207 =====
PING www.a.shifen.com (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_seq=1 ttl=54 time=12.3 ms
64 bytes from 14.215.177.39: icmp_seq=2 ttl=54 time=11.9 ms
===== 10.0.19.208 =====
PING www.a.shifen.com (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_seq=1 ttl=54 time=15.6 ms
64 bytes from 14.215.177.39: icmp_seq=2 ttl=54 time=14.8 ms