Ansible:如何通过 ICMP ping 来检查主机?

问题描述 投票:0回答:1

我在 Ansible 设置方面遇到了一些问题。在执行整个剧本之前,我需要检查主机是否可通过 ICMP 访问,如果没有回复,我想从剧本的执行中跳过该主机。

我当前的剧本如下:

---
- name: Auto_backup_test
  gather_facts: False
  hosts: all
  become: false

  tasks:
    - name: Connection-ping
      delegate_to: localhost
      command: ping -c 2 "{{ inventory_hostname }}"
      register: router_ping

    - name: print_response
      ansible.builtin.debug:
        var: router_ping.rc
        verbosity: 2

因此,剧本应该执行两个 ICMP ping 请求,并将结果保存在

router_ping
寄存器中。

之后,如果请求失败,我希望它检查

router_ping.rc
值,并使用我来决定主机是否为
skipped

当我使用此命令执行剧本时:

ansible-playbook -i /my_inventory/ playbook.yml -vvv

在我的清单中,我有 2 台主机,其中一台应该能够回复 ICMP,另一台 IP 不存在,因此该主机应该会失败。

输出如下:

First host output

Second host output

由此可见,回复ICMP请求的主机工作正常。

但是当主机没有回复 ICMP 请求时,任务就会失败,并且寄存器

router_ping
不会被创建,所以我无法使用该寄存器。第二个主机的输出是我们想要的,但没有创建寄存器,因此我无法评估
router_ping.rc
值来检查主机是否可用。

我怎样做才能表现得更好?

我也尝试使用

ansible.builtin.ping
模块,但由于这并不像我想象的那样工作,因为它总是输出 SUCCESS,所以它对我不起作用。

我尝试了一段时间来使其工作,但即使主机的 IP 地址不存在,我最终总是得到 Success 输出。

linux networking ansible devops icmp
1个回答
0
投票

一个最小的示例手册

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: ICMP ping from Control Node to Remote Node
    delegate_to: localhost # or controlnode.example.com
    command: ping -c 2 "{{ inventory_hostname }}"
    # Because it is an reporting task
    changed_when: false 
    check_mode: false
    failed_when: router_ping.rc == 1 or router_ping.rc > 2 # will result into success for rc 0 and rc 2
    register: router_ping

  - name: Show Return Code
    debug:
      msg: "{{ router_ping.rc }}"

将产生

的输出
TASK [ICMP ping from Control Node to Remote Node] ******
ok: [test1.example.com -> localhost]
ok: [test1.nonexisting.example.com -> localhost]
ok: [test2.example.com -> localhost]
ok: [test2.nonexisting.example.com -> localhost]

TASK [Show Return Code] ********************************
ok: [test1.example.com] =>
  msg: '0'
ok: [test1.nonexisting.example.com] =>
  msg: '2'
ok: [test2.example.com] =>
  msg: '0'
ok: [test2.nonexisting.example.com] =>
  msg: '2'

PLAY RECAP **********************************************************************************************************
test1.nonexisting.example.com : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
test1.example.com  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
test2.example.com : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
test2.nonexisting.example.com  : ok=2    changed=0    unreachable=0    failed=0

通过此 (

router_ping.rc
),可以测试主机是否可解析且可访问 (
0
) 或不可 (
2
)。然而,对于进一步的 playbook 处理来说,这似乎不是一个好的做法,因为 Ansible 已经实现了一些对无法访问的主机的处理。

更多文档

我想推荐阅读有关

终于以某种方式

类似问答


© www.soinside.com 2019 - 2024. All rights reserved.