Skip to main content

Ansible Modules

Ansible Ping Module: Check if Host is Reachable

Quickly test if a node is available with Ansible ping command.

β€ŒThe Ansible ping module is used to test the connection between the Ansible control node (where the playbooks and commands are executed) and the managed nodes (the remote systems you want to manage).

This Ansible module helps verify that Ansible can communicate with your hosts, ensuring they are reachable and ready for further automation tasks.

πŸ“‹
It doesn't perform an ICMP ping but rather checks the connection through the Ansible Python API.

In this guide, you will explore what is ping module and how to use it inside playbooks with practical examples.

Prerequisites

To proceed with this tutorial, you will need the following:

  • An Ansible management node with Ansible installed and configured.
  • SSH key-based authentication between the management node and target nodes.

Ansible ping command syntax

The basic syntax for using the ping command in Ansible is:

ansible <TARGET> -m ping [OPTIONS]

Here's a breakdown of the components:

  • ansible: The Ansible executable command.
  • <TARGET>: This can be a single hostname, a group of hosts defined in your inventory file, or a combination using wildcards or inventory patterns.
  • -m ping: Specifies the ping module to be used for this task.
  • [OPTIONS]: Optional arguments to customize the ping behavior, which we'll explore in the examples.
  • -k: Specify the SSH private key file to use for authentication.
  • --become: Escalate privileges to a different user on the remote host for the ping operation.
  • -v: Increase verbosity for more detailed output.

Example 1: Pinging a single host

You can use the Ansible command with your desired hostname and the -m option to specify the ping module.

ansible host1 -m ping

This command attempts to establish an SSH connection with host1 and verifies the presence of a usable Python interpreter. If successful, it will output:

Ping a single host

Example 2: Pinging a group of hosts

Assuming you have a group named webservers defined in your inventory file containing multiple server hostnames. In this case, you can run the following command to ping the all host defined in the inventory file.

ansible webservers -m ping

This command will attempt to ping each server in the webservers group one by one. The output will display the reachability status for each server.

Ping a group of hosts

Here is the explanation of the above command:

  • ansible: The main Ansible command.
  • webservers: The name of the group containing the hosts you want to ping in your inventory file.
  • -m ping: Instructs Ansible to use the ping module.

Conditional play execution based on ping results

To execute a set of tasks conditionally based on the results of the ping module, you can use a combination of Ansible's block and when constructs.

This example shows how to conditionally run tasks in a playbook based on whether pinging specific hosts is successful.

---
- hosts: webservers
  tasks:
    - name: Ping web servers
      ping:
      register: ping_result

    - name: Install Nginx only on reachable servers
      apt:
        name: nginx
        state: present
      when: 
        - ping_result is not failed
        - ping_result.ping == 'pong'

The above playbook uses the when condition ensures that the apt task to install Nginx only runs on servers that responded to the ping. This avoids unnecessary attempts on unreachable hosts.

Execute task based on ping result

Handling connection issues and retries

To handle connection issues and retries with the ping module in Ansible, you can use a combination of the retries, delay, and until parameters in your playbook. This approach allows you to attempt multiple pings with a delay between each attempt until a host responds.

Here's how to set this up in your Ansible playbook:

- hosts: database_servers
  vars:
    ping_failed: []

  tasks:
    - name: Ping database server with retries
      ping:
      register: ping_result
      until: ping_result is succeeded
      retries: 3
      delay: 5  # Wait 5 seconds between retries
      ignore_errors: yes  # Ensure the task does not fail the play on the first failure

    - name: Collect ping results
      set_fact:
        ping_failed: "{{ ping_failed + [inventory_hostname] }}"
      when: ping_result is failed

    - name: Fail the playbook if any ping fails after retries
      fail:
        msg: "Failed to reach the following database servers after retries: {{ ping_failed }}"
      when: ping_failed | length > 0

This example retries the ping three times for each server in the database_servers group. If none of the pings succeed, the playbook fails with an informative message.

Handle connection issue and retries

Collecting facts from reachable hosts

The ping module can be used in conjunction with fact gathering to check host connectivity and collect facts from reachable hosts.:

---
- hosts: all
  gather_facts: yes  # Gather facts from all hosts

  tasks:
    - name: Collect facts from reachable hosts
      ping:
      register: ping_result  # Register the result of the ping task

    - name: Display OS information of reachable hosts
      debug:
        msg: "OS Name: {{ ansible_os_family }} {{ ansible_distribution }}"
      when: ping_result.ping == "pong"  # Only display facts for reachable hosts

This playbook gathers facts from all hosts and then displays the operating system information (family and distribution) only for those that responded to the ping.

Collect facts from reachable hosts

Conclusion

In this guide, I've covered the basic syntax and provided practical examples of how to use the ping module. We demonstrated how to ping all hosts, specific groups of hosts, and individual hosts directly from the command line. Additionally, I've shown how to incorporate the ping module into a playbook for more structured testing.

If you are new to Ansible and want to learn it from scratch, our Ansible tutorial series will be of great help. It's written for the RHCE exam, but it helps you the same whether you are preparing for the exam or not.

RHCE Ansible EX294 Exam Preparation Course
Learn all the essentials of Ansible with this hands-on tutorial series. It is ideal for RHCE Ansible EX294 exam preparation.
✍️
Author: Hitesh Jethwa has more than 15+ years of experience with Linux system administration and DevOps. He likes to explain complicated topics in easy to understand way.
LHB Community