您的剧本存在一些问题。首先是您尝试在远程主机上同时执行shell 和setup 任务,如果该主机不可用,这当然不会工作。
在远程主机上运行ping 任务甚至没有意义:你想在本地主机上运行它,使用委托。我们可以这样做,将每个主机的可用性记录为主机变量:
---
- hosts: all
gather_facts: false
tasks:
- delegate_to: localhost
command: ping -c1 "{{ hostvars[inventory_hostname].ansible_host|default(inventory_hostname) }}"
register: ping
ignore_errors: true
- set_fact:
available: "{{ ping.rc == 0 }}"
您正在尝试针对您的远程主机运行 setup 模块,但这仅在远程主机可用时才有意义,因此我们需要以 ping 任务的结果为条件:
- setup:
filter: "ansible_*"
when: ping.rc == 0
有了这些,我们就可以生成一个文件,其中包含有关每个主机的可用性信息。我在这里使用lineinfile,因为这就是您在示例中使用的,但如果我自己写这个,我可能会使用template 任务:
- hosts: localhost
gather_facts: false
tasks:
- lineinfile:
dest: ./available.txt
line: "Host: {{ item }}, connection={{ hostvars[item].available }}"
regexp: "Host: {{ item }}"
create: true
loop: "{{ groups.all }}"
当然,在您的示例中,您试图包含有关主机的各种其他事实:
line: 'Host:{{ inventory_hostname }},OS:{{ ansible_distribution }},Kernel:{{ansible_kernel}},OSVersion:{{ansible_distribution_version}},FreeMemory:{{ansible_memfree_mb}},connection:{{ping_status.rc}}'
如果目标主机不可用,这些事实将不可用,因此您需要使用 {% if <condition> %}...{% endif %} 构造使所有这些都成为条件:
line: "Host:{{ item }},connection:{{ hostvars[item].available }}{% if hostvars[item].available %},OS:{{ hostvars[item].ansible_distribution }},Kernel:{{ hostvars[item].ansible_kernel }},OSVersion:{{ hostvars[item].ansible_distribution_version }},FreeMemory:{{ hostvars[item].ansible_memfree_mb }}{% endif %}"
这使得最终的剧本看起来像这样:
---
- hosts: all
gather_facts: false
tasks:
- delegate_to: localhost
command: ping -c1 "{{ hostvars[inventory_hostname].ansible_host|default(inventory_hostname) }}"
register: ping
ignore_errors: true
- set_fact:
available: "{{ ping.rc == 0 }}"
- setup:
when: ping.rc == 0
- hosts: localhost
gather_facts: false
tasks:
- lineinfile:
dest: ./available.txt
line: "Host:{{ item }},connection:{{ hostvars[item].available }}{% if hostvars[item].available %},OS:{{ hostvars[item].ansible_distribution }},Kernel:{{ hostvars[item].ansible_kernel }},OSVersion:{{ hostvars[item].ansible_distribution_version }},FreeMemory:{{ hostvars[item].ansible_memfree_mb }}{% endif %}"
regexp: "Host: {{ item }}"
create: true
loop: "{{ groups.all }}"