Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 29 ยท Core Concepts

Ad-Hoc Commands

Run one-off tasks on many servers with Ansible ad-hoc commands: ping, command, shell, copy, apt and service, plus -b, -l, -i and forks, and when to use them.

An ad-hoc command is a single Ansible module call typed straight into your terminal. There is no playbook and no file to write: you say which hosts, which module and which arguments, and Ansible runs it on all of them in parallel. It is the quickest way to ask "what is the uptime on all web servers?" or to restart a service on five machines at once.

Ad-hoc commands are also the best way to learn modules, because you see exactly what one module does with one set of arguments. Everything you learn here carries over to playbooks, where the same modules appear as tasks. The commands below are read-only examples for your own terminal; the stand-ins at the end imitate how Ansible dispatches a module to a list of hosts.

The shape of the command

Terminal
ansible <pattern> -i <inventory> -m <module> -a "<arguments>" [options]
  • <pattern> chooses hosts from the inventory (all, web, web:db, see Inventory).
  • -i names the inventory file or folder. You can skip it once ansible.cfg sets a default.
  • -m is the module. If you omit it, Ansible uses command.
  • -a gives the module's arguments, usually as key=value pairs separated by spaces. The command and shell modules take a plain command line instead.

A first example that needs nothing but SSH access:

Terminal
ansible web -i inventory/hosts.ini -m ping

Running commands and reading output

To run a program on every web server:

Terminal
ansible web -i inventory/hosts.ini -a "uptime"
TEXT
web1.example.com | CHANGED | rc=0 >>
 14:02:11 up 3 days,  2:40,  1 user,  load average: 0.08, 0.03, 0.01
web2.example.com | CHANGED | rc=0 >>
 14:02:11 up 12 days,  9:15,  0 users,  load average: 0.00, 0.01, 0.00

Each block starts with the host, a status (SUCCESS, CHANGED, FAILED, UNREACHABLE) and, for command-type modules, the exit code rc. Do not be surprised that a harmless uptime says CHANGED: the command module cannot know whether a program changed anything, so it assumes it did. The modules lesson shows how to control that.

The command module runs the program directly, without a shell. So pipes, redirects, && and $VARIABLES do not work. When you need them, use shell:

Terminal
ansible web -m ansible.builtin.shell -a "ps aux | grep -c nginx"

Prefer command when you can: it is safer, because nothing is interpreted by a shell.

A tour of useful modules

Gather facts about a host (the setup module returns hundreds of values):

Terminal
ansible web -m ansible.builtin.setup -a "filter=ansible_distribution*"

Copy a file to the managed nodes:

Terminal
ansible web -m ansible.builtin.copy -a "src=./motd dest=/etc/motd owner=root mode=0644" -b

Run it a second time and the status is SUCCESS with "changed": false, because the file already matches. That is idempotence at work.

Install a package (needs administrator rights, hence -b):

Terminal
ansible web -m ansible.builtin.apt -a "name=nginx state=present update_cache=yes" -b

Control a service:

Terminal
ansible web -m ansible.builtin.service -a "name=nginx state=restarted" -b

Create a user, fetch a URL, check disk space:

Terminal
ansible all -m ansible.builtin.user -a "name=deploy shell=/bin/bash" -b
ansible all -m ansible.builtin.get_url -a "url=https://example.com/app.tgz dest=/tmp/app.tgz"
ansible all -a "df -h /"

Look at the pattern: state=present, state=restarted. You describe the result. The module decides whether work is needed. To read the documentation of any module offline, use ansible-doc ansible.builtin.copy.

Module names in this tutorial are written in full, ansible.builtin.copy. The short form copy still works, but the full name (the fully qualified collection name) is unambiguous. See Collections, Galaxy and Reusable Content.

The options you will use all the time

Option Purpose
-b (--become) Run with higher privileges, usually sudo.
-K (--ask-become-pass) Prompt for the sudo password.
-u user SSH login name.
-l pattern (--limit) Restrict the run to a subset of the chosen hosts.
-f N (--forks) How many hosts to work on in parallel; the default is 5.
-i path Inventory file or directory.
-C (--check) Dry run: report what would change. Not all modules support it.
-v, -vvv More detail; -vvv shows the SSH connection details.
-e "k=v" Pass extra variables.

Privileges deserve one more sentence. Without -b, the module runs as the SSH user. Installing packages, writing to /etc or restarting system services needs root, so those commands fail with a permission error unless you add -b. Details about methods and users come in SSH, Privilege Escalation and Hardening.

Parallelism works in batches. With 20 hosts and the default 5 forks, Ansible handles five hosts at a time and moves on as each finishes. A higher -f finishes sooner but loads the control node and the network more.

flowchart LR
    P["pattern + -l limit<br/>pick the hosts"] --> B["forks: batches of N hosts"]
    B --> M["module runs on<br/>each host"]
    M --> R["one result per host:<br/>SUCCESS / CHANGED / FAILED / UNREACHABLE"]

An ad-hoc run selects hosts, works through them in batches, and reports one result per host.

When ad-hoc is the right tool

Good uses:

  • Quick checks: disk space, uptime, which kernel is running, whether a file exists.
  • One-off actions: restart a service, reboot a group of machines, copy an emergency file.
  • Experiments: try a module on your lab host before putting it in a playbook.

Poor uses:

  • Anything you will need again or that someone else must repeat. Put it in a playbook so it lives in version control.
  • Multi-step work where the order matters.

A handy rule: the second time you type the same ad-hoc command, write a playbook. The next lesson, Playbooks and YAML Essentials, shows how.

Stand-in: dispatching a module to many hosts

The real tool connects over SSH and runs Python modules. This stand-in keeps only the control flow: pick hosts (with a limit), split them into batches of forks, check privileges, call a module function, and print SUCCESS or CHANGED. The modules are tiny pretend versions of ping, copy, apt and service.

JS Dispatching modules to a host list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Follow the output from top to bottom. The ping runs with forks of 2, so three hosts become two batches. The first apt call fails without -b. With -b, web2 and web3 report CHANGED while web1, which already had nginx, reports SUCCESS. Running it again is all SUCCESS: the stand-in modules are idempotent, like the real ones. The last call limits the run to web3, whose file already has the right content.

Stand-in: reading key=value arguments

Module arguments such as "name=nginx state=present" are just text that the tool splits into a dictionary (the command module is the exception: it takes the whole string as a command line). This stand-in handles quoted values with spaces.

JS Parsing the -a argument string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that every value stays a string ("yes", "0644"). Real modules convert them to their own types, which is why mode=0644 works but a bare mode=644 would mean something different. Quoting and types matter even more in YAML; the next lesson takes a careful look.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run ansible web -a "uptime" with no -m option. Which module is used?

    When -m is omitted the command module runs, which executes the program directly without a shell.
  2. 2. Which ad-hoc command needs a shell because it uses a pipe?

    The command module does not interpret pipes. The shell module passes the line to a shell, so the pipe works.
  3. 3. An apt install via an ad-hoc command fails with a permission error. What is the most likely fix?

    Installing packages needs root. -b (become) runs the module through sudo or a similar method.
  4. 4. What does -l web1 do on top of the pattern all?

    --limit narrows the hosts chosen by the pattern, which is a safe way to try a command on one machine first.
  5. 5. When should an ad-hoc command become a playbook?

    One-off checks and actions suit ad-hoc commands. Anything repeatable belongs in a playbook under version control.

Summary

  • An ad-hoc command is ansible <pattern> -m <module> -a "<args>"; with no -m the command module runs.
  • command runs a program without a shell, shell allows pipes and redirects; prefer command.
  • Modules such as copy, apt and service take key=value arguments that describe the desired result.
  • -b escalates privileges, -l limits hosts, -f sets parallel forks (default 5), -i names the inventory.
  • Results are reported per host as SUCCESS, CHANGED, FAILED or UNREACHABLE.
  • Use ad-hoc commands for quick checks and one-off actions; use playbooks for anything repeatable.

Next: Playbooks and YAML Essentials