Ansible ad hoc commands let you run one-off tasks directly from the CLI without writing a playbook.
ansible <host-pattern> -m <module> -a "<module arguments>" [options]
Examples:
ansible all -m ping
command module by default):ansible webservers -a "uptime"
ansible dbservers -m command -a "id"
-i inventory.ini – inventory file if not using default.
-u username – remote user.
-b / --become – use privilege escalation (sudo).
ansible all -m copy -a "src=/tmp/file dest=/etc/file" -b
-k – ask for SSH password, -K – ask for become password.
-f 10 – set forks, i.e., parallelism.
Copy a file to all hosts:
ansible all -m copy -a "src=/path/to/file dest=/path/on/remote"
Install a package with privilege escalation:
ansible app -b -m yum -a "name=vim state=latest"
# or Debian/Ubuntu:
ansible app -b -m apt -a "name=vim state=latest update_cache=yes"
Manage a service:
ansible web -b -m service -a "name=nginx state=restarted"
Check a file’s status:
ansible all -m stat -a "path=/etc/environment"
Create a directory in an idempotent way:
ansible nodes -m file -a "path=/BYANSIBLE_3 state=directory"
Use ad hoc for:
Use playbooks for: