Skip to content

Expert · Ansible fundamentals · topic 46 of 57 · 30 min

Ad-hoc commands and ansible-doc

Explanation

An ad-hoc command runs one module on many hosts from the command line: ansible PATTERN -m MODULE -a "ARGUMENTS". It is good for quick checks and one-off fixes. Use -b to become root. ansible-doc shows every module's options and examples, offline.

When to use ad-hoc commands

Before writing a playbook, you often want a quick answer or a one-off change: "is SSH working on all hosts?", "what is the uptime of the database servers?", "restart httpd on web02 now". An ad-hoc command does this in one line, using the same modules and inventory as playbooks.

bash
$ ansible all -m ansible.builtin.ping
web01.example.com | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
$ ansible dbservers -m ansible.builtin.command -a "uptime"
db01.example.com | CHANGED | rc=0 >>
 18:20:11 up 12 days,  3:02,  0 users,  load average: 0.08, 0.05, 0.01
$ ansible webservers -b -m ansible.builtin.dnf -a "name=httpd state=present"
web01.example.com | CHANGED => { ... "msg": "", "rc": 0, "results": ["Installed: httpd-2.4.57-11.el9_4.x86_64", ...] }
web02.example.com | SUCCESS => { "changed": false, "msg": "Nothing to do", ... }
$ ansible web02.example.com -b -m ansible.builtin.service -a "name=httpd state=restarted"
The module name uses its full name (FQCN): collection.module, here ansible.builtin.

The parts of the command

PartMeaningExample
PATTERNWhich hosts: a host, group, all, or combinationswebservers, all, 'web*', 'webservers:!web03.example.com'
-mThe module-m ansible.builtin.user
-aModule arguments as key=value pairs-a "name=ravi state=present"
-bbecome (sudo) for this command-b
-iUse a different inventory-i prod_inventory
-uRemote user-u devops
--limitRestrict further--limit web01.example.com

command, shell and real modules

ansible.builtin.command runs a program directly, without a shell, so pipes (|), redirections (>) and variables like $HOME do not work. ansible.builtin.shell runs through /bin/sh, so they do. Both always report "changed", because Ansible cannot know if your command changed anything. Prefer a specific module whenever one exists: it is idempotent and reports honestly.

bash
# not idempotent: adds the line every time
$ ansible all -b -m ansible.builtin.shell -a "echo '10.0.0.5 db01' >> /etc/hosts"
# idempotent: adds it only if missing
$ ansible all -b -m ansible.builtin.lineinfile -a "path=/etc/hosts line='10.0.0.5 db01'"
# create a user everywhere
$ ansible all -b -m ansible.builtin.user -a "name=ravi groups=wheel append=yes"
# copy a file with owner and mode
$ ansible webservers -b -m ansible.builtin.copy -a "src=motd dest=/etc/motd owner=root mode=0644"

ansible-doc: the offline manual

bash
$ ansible-doc -l | grep -i firewall               # listed only if ansible.posix is installed
ansible.posix.firewalld        Manage arbitrary ports/services with firewalld
$ ansible-doc ansible.builtin.dnf | less        # every option, then EXAMPLES at the end
$ ansible-doc -s ansible.builtin.user           # a short snippet of all options
In exams without internet, ansible-doc plus the EXAMPLES section is how you get module syntax right.

Common mistakes

  • Forgetting -b for tasks that need root: "You need to be root to perform this command."
  • Using command with a pipe: the | is passed as text to the program. Use shell, or better, a module.
  • Quoting: wrap the whole -a value in double quotes and values with spaces in single quotes inside it.
  • Running a risky ad-hoc command against all. Try one host first with --limit.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Ad-hoc commands and ansible-doc · 1/6

ansible PATTERN -m MODULE -a "ARGS"

An ad-hoc command runs one module on many hosts from the command line.

Prefer a video by a teacher? Find free videos on “ansible ad hoc commands tutorial ansible-doc modules” on YouTube ↗

In real life: Checking free disk space before Diwali sales

Before the Diwali sale, the platform team of an online retailer in Bengaluru wants to know which of its 120 app servers are low on disk. Instead of logging into each one, they run a single ad-hoc command and sort the output. Three servers are above 85%, and they get cleaned up the same day.

bash
$ ansible appservers -m ansible.builtin.shell -a "df --output=pcent / | tail -1" -o | sort -t'>' -k2 -r | head -3
app-117 | CHANGED | rc=0 | (stdout)  91%
app-042 | CHANGED | rc=0 | (stdout)  88%
app-009 | CHANGED | rc=0 | (stdout)  86%
-o prints one line per host.

Practice (0/3 done)

Task 1 · Question

Which ad-hoc command installs httpd on the webservers group?

Task 2 · Question

Why is ansible.builtin.lineinfile better than shell "echo ... >> file" for adding a line?

Task 3 · Practice

Using only ad-hoc commands against your lab inventory: check connectivity, create the group "devs" and user "meena" in it, put a message in /etc/motd, make sure chronyd is started and enabled, and show the uptime of every host. Run each command twice and note which ones say changed the second time.

Quick quiz

Question 1

1.Which module should you use to run a command that includes a pipe (|)?

Question 2

2.What does -b mean in an ad-hoc command?

Question 3

3.Which command shows a module's options and examples without internet?

Question 4

4.What does "ansible all -m ansible.builtin.ping" check?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which module should you use to run a command that includes a pipe (|)?

Answer: ansible.builtin.shell

command does not use a shell, so pipes do not work.

What does -b mean in an ad-hoc command?

Answer: Become (privilege escalation)

-b = --become.

Which command shows a module's options and examples without internet?

Answer: ansible-doc MODULE

ansible-doc.

What does "ansible all -m ansible.builtin.ping" check?

Answer: That Ansible can log in over SSH and run Python on each host

It is a module round-trip, not ICMP.

Why prefer ansible.builtin.apt over ansible.builtin.shell with "apt-get install -y nginx"?Related

Answer: apt is idempotent and reports changed only when it really changes something

shell runs every time and always reports changed; the apt module checks state first.

From Ansible: inventory and ad-hoc commands

What does ansible-playbook site.yml --check --diff do?Related

Answer: Shows what would change, with file differences, without changing anything

Check mode is a dry run; diff shows the before and after of files.

From Ansible playbooks

What does -C do with ansible-playbook?Related

Answer: Check mode: predict changes without making them

It is a dry run.

From Writing and running playbooks

Which package gives you ansible-playbook on RHEL 9?Related

Answer: ansible-core

ansible-core.

From What Ansible is and how it works

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Ansible fundamentals” before its exam: Writing and running playbooks, Everyday modules and handlers.
  2. Module 9 exam: Ansible fundamentals · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Ansible in depth. 57 topics left in the course before the final exam.

← Previous: Inventory and ansible.cfg