Ansible Ad-Hoc Commands

Ansible Ad-Hoc Commands

Day 56 of 90daysofdevops

What are Ansible Ad-hoc commands

Ansible ad hoc commands are one-line commands used to perform simple tasks on remote systems without the need for complex playbooks. They allow you to execute specific modules on target hosts directly from the command line.

Ad hoc commands are particularly useful for quick tasks, troubleshooting, and one-time operations, providing flexibility and ease of use without the need for writing and maintaining a full playbook.

Ad hoc commands follow the syntax

ansible <host-pattern> -m <module> -a <arguments>

# If you’re using a custom SSH key to connect to the remote servers, 
# you can provide it at execution time with the --private-key

ansible <host-pattern> -m <module> -a <arguments> --private-key=~/.ssh/custom_id
  • <host-pattern> specifies the target hosts or groups of hosts where the command should be executed.

  • <module> refers to the Ansible module to be used for the task. Modules provide functionality for different operations like file manipulation, package management, user management, etc.

  • <arguments> are optional arguments specific to the module, allowing customization and specifying the desired behavior.


Ad-hoc command to ping 3 servers from the inventory file

# For selecting indivisual servers
ansible server1:server2:server3 -m ping

# For selecting all servers listed on inventory file
ansible all -m ping

Ad-hoc command to check system uptime

ansible all -m command -a uptime

Ad-hoc command to check the free memory or memory usage of hosts

ansible all -a "free -m"

Ad-hoc command to get physical memory allocated to the host

 ansible all -m shell -a "cat /proc/meminfo|head -2"

Ad-hoc command to check whether Nginx is installed on all the servers

ansible all -b -m shell -a 'nginx -v'

Ad-hoc command to check whether Docker is installed on all the servers

ansible all -b -m shell -a 'docker --version'

Ad-hoc command to check Python is installed on all the servers

ansible all -b -m shell -a 'python --version'


Thank You,

I want to express my deepest gratitude to each and every one of you who has taken the time to read, engage, and support my journey.

Feel free to reach out to me if any corrections or add-ons are required on blogs. Your feedback is always welcome & appreciated.

~ Abhisek Moharana 🙂