# ansible / automation / ad-hoc
Execute Quick Tasks with Ad-Hoc Commands
An Ansible ad-hoc command is a powerful one-line command used to perform quick tasks on remote servers without the overhead of writing a full YAML playbook.
Why Use Ad-Hoc Commands?
Playbooks are designed for repeatable, complex automation. But sometimes, you just need to restart a service right now, or check the disk space across 50 servers instantly.
Perfect Use Cases
- speed
Fast Execution: You don't want to create and manage a YAML playbook for a single action.
- diagnostics
Quick Checks: Testing connectivity, verifying configurations, or gathering simple facts.
- incident response
Troubleshooting: Immediate actions like restarting a crashed service or clearing a full log directory.
- disposable
One-Time Tasks: Tasks that are temporary and don't need to be committed to version control.
System & Execution Operations
These are your bread-and-butter commands for checking inventory, verifying access, and running arbitrary shell commands across your fleet.
Module Differences
The command module is secure and predictable, but it does not process bash operators. If you need to use pipelines (|), redirects (>), or env variables, you must use the shell module instead.
Packages, Services & Users
Key Parameters Explained
- -b
Become: Tells Ansible to execute the command with root/sudo privileges. Required for package installations and service restarts.
- state=present
Declarative State: Ensures the package or user exists. If it already does, Ansible does nothing.
- append=yes
Safe Group Addition: When adding a user to a group, this ensures they are not accidentally removed from their other existing groups.
File Operations & Sync
Need to pull logs down from 50 servers at once? Or push a hotfix config file out to an entire cluster? Ad-hoc commands handle file operations flawlessly.
State = Absent
In Ansible, you don't run a "delete" command. Instead, you use the file module and set the state to absent. Ansible will wipe the file or directory if it exists, and gracefully succeed if it's already gone.
Lessons from running this in production
The template module can also be used ad-hoc (ansible -m template -a "src=temp dest=/tmp"), but templates usually rely on Jinja2 variables defined in playbooks, making them much more useful inside standard YAML files.
Because ad-hoc commands are typed directly into your terminal, they are saved in your shell's .bash_history. Never pass plaintext passwords or sensitive secrets via ad-hoc command arguments.
Ad-hoc commands respect your inventory file completely. You can target all, a specific group like webservers, or even a single specific host by its hostname.