Skip to main content
In this article, you will learn how to run ad hoc commands with Ansible. Although YAML-based playbooks are the recommended method for automating tasks—enabling reusability, version control with Git, and easy sharing—ad hoc commands provide a quick and efficient alternative for testing modules, verifying connectivity, or gathering one-off information from multiple servers.
The Ansible ping module is used to verify SSH connectivity to target machines using the configured credentials, not for performing an ICMP ping.

Using a YAML Playbook for Connectivity Testing

For administrators managing virtual machines, a simple playbook using the ping module is an excellent way to test connectivity. Below is an example playbook that pings all target servers:
To run the playbook, execute the following command in your terminal:

Executing Ad-Hoc Commands Directly

If you prefer not to create a playbook, you can achieve the same result using an ad hoc command. Use the -m option to specify the module and designate the target hosts. The command below pings all servers:
When executed, the output appears in JSON format for each host, similar to the following:

Running Arbitrary Commands

To run an arbitrary command on all hosts, use the -a option to pass the command directly. For instance, to display the contents of the /etc/hosts file, run:
The output will be similar to this:

Privilege Escalation with Ad-Hoc Commands

You can also include privilege escalation options (such as become or become_user) with these ad hoc commands, just as you would when using a playbook. This flexibility makes ad hoc commands a powerful tool for managing your infrastructure on the fly. Continue exploring additional methods to effectively utilize ad hoc commands in Ansible for efficient infrastructure management.

Watch Video

Practice Lab