在 写文件的同时,再加一个 debug
任务,把统计信息直接打印在终端。这样你执行完 ansible-playbook
就能立刻看到成功/失败情况。
最终 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
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
- name: Show summary in terminal
debug:
msg: |
===== 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(', ') }}
执行
ansible-playbook -i /etc/ansible/hosts/inventory.ini ping_baidu.yml
终端输出示例
TASK [Show summary in terminal] ***********************************************
ok: [localhost] => {
"msg": "===== SUMMARY =====\nSuccess hosts (1):\n10.0.19.207\n\nFailed hosts (1):\n10.0.19.208"
}
文件 /tmp/ping_results/all.log
同时也会保存完整的日志 + 统计。