Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible playbook to check server reachability from target host

Tags:

ansible

I am using the following playbook to check connectivity from target host 192.168.153.31 to 8.8.8.8

---
- hosts: 192.168.153.31
  gather_facts: no

  tasks:
  - name: Ping net1
    shell:  |
      ping -c3 8.8.8.8 >/dev/null
      if [ $? -eq 0 ]
      then
        echo "ok"
      else
        echo "nok"
      fi
    ignore_errors: true
    register: output

  - name: end playbook
    meta: end_host
    when: output.stdout == 'nok'

based on output I have remaining tasks to be executed. Is there any better way to verify connectivity?

like image 978
Bindu G Avatar asked Oct 24 '25 14:10

Bindu G


1 Answers

You can simplify the code by testing rc, e.g.

    - command: ping -c3 8.8.8.8
      ignore_errors: true
      register: output
    - meta: end_host
      when: output.rc != 0

If you can run a playbook at 192.168.153.31 and want to test if Ansible can connect to the target use wait_for_connection, e.g.

---
- hosts: 8.8.8.8
  gather_facts: no

  tasks:
    - name: Wait for connection to net1
      wait_for_connection:
like image 181
Vladimir Botka Avatar answered Oct 26 '25 11:10

Vladimir Botka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!