Ansible Tutorial · Getting Started · Lesson 4 of 20
Ansible Ad-hoc Commands
Run one-off tasks without writing a playbook.
What is an ad-hoc command?
An ad-hoc command runs a single Ansible module against one or more hosts from the command line. It is useful for quick tasks like checking connectivity, gathering information or making a small change.
Syntax
ansible <pattern> -i <inventory> -m <module> -a "<arguments>"
-mselects the module (default iscommand).-apasses arguments to the module.-ipoints to the inventory file.--become(-b) runs with sudo.
Common modules
ping — test connectivity
ansible all -i inventory.yml -m ping
This does not send an ICMP ping. It connects over SSH, runs a tiny Python script and returns pong.
command and shell
ansible webservers -i inventory.yml -m command -a "uptime"
ansible webservers -i inventory.yml -m shell -a "df -h | grep /dev/sda"
command runs a command directly (no shell features like pipes). shell runs through /bin/sh,
so pipes and redirects work.
copy — send a file
ansible webservers -i inventory.yml -m copy -a "src=./app.conf dest=/etc/app.conf mode=0644" --become
apt / yum — install packages
ansible webservers -i inventory.yml -m apt -a "name=nginx state=present" --become
service — manage services
ansible webservers -i inventory.yml -m service -a "name=nginx state=started enabled=yes" --become
file — create directories, set permissions
ansible webservers -i inventory.yml -m file -a "path=/var/www/app state=directory owner=www-data mode=0755" --become
Limiting and filtering
ansible webservers -i inventory.yml -m ping --limit web-1.example.com
ansible 'webservers:&production' -i inventory.yml -m ping
--limit restricts the run to specific hosts within the pattern.
ansible localhost -m ping
Output
localhost | SUCCESS => {
"changed": false,
"ping": "pong"
}Run this on your computer — see “Get Started” for setup.
ansible localhost -m command -a "uname -s"
Output
localhost | CHANGED | rc=0 >> Linux
Run this on your computer — see “Get Started” for setup.
ansible localhost -m setup -a "filter=ansible_hostname"
Output
localhost | SUCCESS => {
"ansible_facts": {
"ansible_hostname": "control-node"
},
"changed": false
}Run this on your computer — see “Get Started” for setup.
Test yourself
What is the difference between the command and shell modules?
command uses SSH, shell uses WinRMcommand runs directly, shell runs through /bin/shcommand is faster, shell is slowerThere is no difference
Show answer
Answer: command runs directly, shell runs through /bin/sh
The shell module processes the command through /bin/sh, enabling pipes, redirects and environment variables. The command module runs the executable directly.