Ad-Hoc Commands
Before writing playbooks, you can use ad‑hoc commands to run single tasks on managed nodes. Ad‑hoc commands are great for quick checks, reboots, or installing packages without writing a full playbook.
Ad‑Hoc Command Syntax
ansible <host-pattern> -m <module> -a <arguments> -i <inventory>host-pattern: a single host, a group, orall.-m module: the module to use (e.g.,ping,command,copy).-a arguments: arguments for the module.-i inventory: inventory file (optional if default).
Common Ad‑Hoc Examples
Ping all hosts (tests connectivity):
ansible all -m pingRun a shell command on a specific host:ansible web1 -m command -a "uptime"Install a package on a group of servers (using apt module):ansible webservers -m apt -a "name=nginx state=present" --becomeCopy a file to managed nodes:ansible all -m copy -a "src=/local/file dest=/remote/file"Restart a service:ansible webservers -m service -a "name=nginx state=restarted" --becomeImportant Flags
--become(or-b): run the command with privilege escalation (sudo).-u username: connect as a different SSH user.-v(verbose): see detailed output.--check: dry run without making changes.
When to Use Ad‑Hoc vs. Playbooks
Ad‑hoc commands are great for one‑time tasks. For anything you’ll repeat or need to document, write a playbook.
Two Minute Drill
- Ad‑hoc commands run single tasks without playbooks.
- Syntax:
ansible pattern -m module -a "args". - Use
--becomefor sudo privileges. - Common modules:
ping,command,apt,copy,service.
Need more clarification?
Drop us an email at career@quipoinfotech.com
