好的,那我帮你加一个 汇总统计,在 all.log
的最后输出:
这样你不用手工翻日志,就能一眼看到执行结果。
保存为 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
ignore_errors: yes # 即使失败也继续执行
- name: Collect results with status
set_fact:
ping_summary: "{{ ping_summary | default([]) + ['===== ' + inventory_hostname + ' =====\n' + (ping_result.stdout | default('FAILED'))] }}"
ping_success: "{{ (ping_success | default([])) + ([inventory_hostname] if ping_result.rc == 0 else []) }}"
ping_failed: "{{ (ping_failed | default([])) + ([inventory_hostname] if ping_result.rc != 0 else []) }}"
- 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 with summary
copy:
content: |
{{ hostvars | dict2items | selectattr('value.ping_summary','defined') | map(attribute='value.ping_summary') | sum(start=[]) | join('\n\n') }}
===== SUMMARY =====
Success hosts ({{ hostvars | dict2items | map(attribute='value.ping_success') | select('defined') | sum(start=[]) | length }}):
{{ hostvars | dict2items | map(attribute='value.ping_success') | select('defined') | sum(start=[]) | join(', ') }}
Failed hosts ({{ hostvars | dict2items | map(attribute='value.ping_failed') | select('defined') | sum(start=[]) | length }}):
{{ hostvars | dict2items | map(attribute='value.ping_failed') | select('defined') | sum(start=[]) | join(', ') }}
dest: /tmp/ping_results/all.log
/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 =====
FAILED
===== SUMMARY =====
Success hosts (1):
10.0.19.207
Failed hosts (1):
10.0.19.208
要不要我再帮你把这个 统计信息输出到终端(stdout),而不仅仅写文件?这样你运行完 Playbook 就能立刻看到成功/失败情况。