What are Ad-hoc Commands?
• Ad-hoc commands are one-liners in Ansible used for quick tasks across multiple servers.
• They’re perfect for testing connectivity, checking system state, restarting services, or gathering facts.
• Think of them as:
• Ad-hoc command - like a Linux one-liner
• Playbook - like a full shell script with logic
Step-by-step tasks
Task 1: Ping 3 servers from the inventory file
Assume your inventory file is /home/ubuntu/ansible/hosts with group [web] containing 3 servers.
ansible web -i /home/ubuntu/ansible/hosts -m ping
• web - inventory group
• -m ping - use Ansible’s built-in ping module (not ICMP ping, but SSH + Python check)
• Expected output: each server responds with pong.
Task 2: Check uptime on all servers
Use the command module to run Linux uptime:
ansible web -i /home/ubuntu/ansible/hosts -m command -a "uptime"
• -m command → tells Ansible to run a shell command.
• -a "uptime" → argument to the module (Linux command).
• Output example:
10.0.1.12 | SUCCESS | rc=0 >>
15:22:13 up 2 days, 3:01, 1 user, load average: 0.00, 0.01, 0.05
More useful Ad-hoc examples (optional to try):
- Check disk space
ansible web -i /home/ubuntu/ansible/hosts -m shell -a "df -h"
- Install a package (nginx)
ansible web -i /home/ubuntu/ansible/hosts -m apt -a "name=nginx state=present" --become
- Restart a service
ansible web -i /home/ubuntu/ansible/hosts -m service -a "name=nginx state=restarted" --become
Key Notes
• Use --become when you need sudo/root privileges.
• command vs shell modules:
• command runs simple commands (no pipes, redirects).
• shell runs full shell commands (supports pipes, &&, etc.).
Top comments (0)