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.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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 theping module is an excellent way to test connectivity. Below is an example playbook that pings all target servers:
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:
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:
Privilege Escalation with Ad-Hoc Commands
You can also include privilege escalation options (such asbecome 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.