With the inventory organized and ansible.cfg in place, you are finally going to change things on Aurora Store's servers. An ad hoc command is a single action that Ansible runs against a set of hosts from the command line, without writing any file: checking the disk space on every machine, installing a package on all the web servers, restarting a service on the database… They're the Swiss Army knife of an administrator's day-to-day work. In this lesson you will learn their complete syntax, the difference (and the risks) between command and shell, and how to copy files, manage packages, services and users, reboot machines, query facts, escalate privileges, simulate changes with --check and --diff, and launch long-running tasks in the background. Above all, you will understand why idempotent modules are preferable to running shell commands.

Contents

  1. Complete syntax of an ad hoc command
  2. Ad hoc or playbook: when to use each one
  3. Quick queries: command versus shell
  4. Escalating privileges with --become
  5. Copying files
  6. Managing packages
  7. Managing services
  8. Managing users
  9. Rebooting servers
  10. Querying facts with setup
  11. Simulating changes: --check and --diff
  12. Parallelism, compact output and background tasks
  13. The key lesson: idempotency

  1. Complete syntax of an ad hoc command

ansible <pattern> [-m <module>] [-a '<arguments>'] [options]
Element Required Meaning Example
<pattern> Yes Hosts to act on (lesson 2.1) webservers, 'all:!db1'
-m <module> No Module to run. If omitted, ansible.builtin.command -m ansible.builtin.apt
-a '<arguments>' Depends on the module The module's parameters -a 'name=htop state=present'
Options No Modify how it runs --become, --check, -f 10, -o

Arguments can be written in two ways:

# key=value format (the most common in ad hoc commands)
ansible webservers -m ansible.builtin.apt -a 'name=htop state=present' --become

# JSON format (useful for lists or complex values)
ansible webservers -m ansible.builtin.apt -a '{"name": ["htop", "tree"], "state": "present"}' --become

Always wrap the arguments in single quotes so the shell doesn't interpret spaces, $, * or !. If a value contains spaces, use double quotes inside: -a 'comment="Deployment user"'.

Remember that, thanks to ansible.cfg, you no longer need -i: every command in this lesson is run from ~/aurora-infra.

  1. Ad hoc or playbook: when to use each one

Situation Ad hoc Playbook
One-off query (uptime, disk, a package's version) ✔
Urgent, one-time action (restarting a service that's down) ✔
Checking that a module does what you expect before writing it into a playbook ✔
Configuration that must be maintained over time ✔
Several steps that depend on each other ✔
Something a colleague must be able to repeat or review ✔
Anything that needs to be recorded in git ✔

The rule of thumb: if you're going to do it more than once, or if it changes the desired state of the infrastructure, write it in a playbook. Ad hoc commands aren't versioned; if you install something by hand with an ad hoc command, the aurora-infra repository no longer fully describes what's really on the servers. In this lesson you will use them to learn the modules; in Module 3 you will turn everything into code.

  1. Quick queries: command versus shell

3.1 The default module: command

ansible all -a uptime
ansible all -a 'df -h /'
ansible dbservers -a 'free -m'

Without -m, Ansible uses ansible.builtin.command, which runs the program directly, without going through a shell. Sample output:

web1 | CHANGED | rc=0 >>
 10:15:32 up  2:03,  1 user,  load average: 0.00, 0.01, 0.00
web2 | CHANGED | rc=0 >>
 10:15:32 up  2:03,  1 user,  load average: 0.02, 0.03, 0.00
db1 | CHANGED | rc=0 >>
 10:15:33 up  2:03,  1 user,  load average: 0.05, 0.02, 0.00

As you saw in lesson 1.5, command always reports CHANGED: Ansible has no way of knowing whether an arbitrary command has modified anything.

Since it doesn't use a shell, command doesn't understand pipes (|), redirections (>, <), operators (&&, ;), environment variables ($HOME) or wildcards (*):

ansible web1 -a 'df -h | grep /dev'
web1 | FAILED | rc=1 >>
df: '|': No such file or directory
df: grep: No such file or directory
...

df received | and grep as if they were file system names.

3.2 When you need a shell: shell

ansible all -m ansible.builtin.shell -a 'df -h / | tail -1'
ansible webservers -m ansible.builtin.shell -a 'ps aux --sort=-%mem | head -5'

ansible.builtin.shell runs the command through /bin/sh, so pipes, redirections and variables work.

Aspect command shell
Goes through a shell No Yes (/bin/sh)
Pipes, redirections, &&, $VAR, * No Yes
Risk of command injection Low High if the command includes variable data
Predictable behavior More Less (depends on the shell and the environment)
Idempotent No (except with creates/removes) No (except with creates/removes)
When to use it By default, to run a program Only if you need shell features

Risks of shell:

  • Injection: if part of the command comes from a variable (for example, a file name supplied by someone else), a value such as x; rm -rf /tmp/data would run a second command.
  • Nested quotes: between the local shell, Ansible and the remote shell, quoting quickly gets complicated.
  • A false sense of automation: a shell with apt-get install "works", but it neither reports changes correctly nor is idempotent.

Golden rule: if there's a module for what you want to do, use it. If not, command. And only if you need pipes or redirections, shell.

3.3 creates and removes: a bit of idempotency

Both modules accept two parameters that give them basic idempotency:

# Only runs if /tmp/aurora-init does NOT exist
ansible web1 -a 'touch /tmp/aurora-init creates=/tmp/aurora-init'

Run it twice: the first time you get CHANGED; the second, SUCCESS with the message skipped, since /tmp/aurora-init exists. removes is the opposite: it only runs if the file does exist.

  1. Escalating privileges with --become

Most administration tasks need root permissions. The --become option (or -b) makes Ansible run the module with sudo (you configured it in the [privilege_escalation] section of ansible.cfg):

ansible web1 -a 'cat /etc/shadow'        # FAILED: Permission denied
ansible web1 -a 'head -1 /etc/shadow' -b # CHANGED: shows root's line
Option Meaning
-b, --become Escalate privileges (to root by default)
--become-user <user> Become another user (postgres, for example)
-K, --ask-become-pass Ask for the sudo password (not needed in the lab: vagrant has passwordless sudo)
--become-method <method> Another method (su, doas…); defaults to the one in ansible.cfg (sudo)

Use --become only when needed: it's the principle of least privilege.

  1. Copying files

The ansible.builtin.copy module copies a file from the control node to the servers, or creates one with given contents:

ansible aurora -m ansible.builtin.copy \
  -a 'content="Aurora Store server ({{ inventory_hostname }}). Restricted access.\n" dest=/etc/motd mode=0644' -b
  • content=: the file's contents (an alternative to src=, which points to a local file).
  • dest=: destination path on the server.
  • mode=0644: the file's permissions.
  • {{ inventory_hostname }}: Ansible substitutes each host's name before sending it.

First run: CHANGED on all three. Repeat it: all three respond SUCCESS with "changed": false, because copy compares the contents (using a checksum) and does nothing if the file is already identical. Connect to web1 with ssh web1 and you will see the message when you log in.

To bring files from the servers to the control node there's ansible.builtin.fetch:

ansible dbservers -m ansible.builtin.fetch -a 'src=/etc/os-release dest=/tmp/aurora-fetch/'

The file is saved to /tmp/aurora-fetch/db1/etc/os-release: fetch creates a subdirectory per host so the files don't get mixed up.

  1. Managing packages

Install htop (a process monitor) on all of Aurora's servers:

ansible aurora -m ansible.builtin.apt -a 'name=htop state=present update_cache=true cache_valid_time=3600' -b
Parameter Meaning
name=htop Package to manage (or a comma-separated list: name=htop,tree)
state=present Desired state: installed. Others: absent (uninstalled), latest (latest version)
update_cache=true Runs the equivalent of apt update first
cache_valid_time=3600 …but only if the cache is more than 1 hour old, so it isn't refreshed on every run

Pay attention to the wording: you don't tell Ansible "install htop", but "I want htop to be present". If it's already installed, it does nothing (SUCCESS, green). This is the idempotency you studied in lesson 1.4.

To check the installed version, use a query:

ansible aurora -a 'dpkg-query -W htop'

There's also ansible.builtin.package, which automatically picks the system's package manager (apt, dnf…). You will see it in the next lesson, along with a comparison of the package modules.

  1. Managing services

ansible.builtin.service controls system services. Make sure cron is started and enabled at boot:

ansible aurora -m ansible.builtin.service -a 'name=cron state=started enabled=true' -b
state Effect Idempotent?
started Starts the service if it's stopped Yes
stopped Stops it if it's running Yes
restarted Always restarts it No (always CHANGED)
reloaded Always reloads the configuration No

enabled=true ensures it starts when the system boots. On Ubuntu 24.04, cron is already running, so you will see SUCCESS with no changes. Try a restart:

ansible db1 -m ansible.builtin.service -a 'name=cron state=restarted' -b

It always reports CHANGED: restarting is an action, not a state. In playbooks you will learn to restart services only when their configuration changes (with handlers, Module 5).

  1. Managing users

Aurora Store will need its own user to deploy the web application. Create it on the web servers with ansible.builtin.user:

ansible webservers -m ansible.builtin.user \
  -a 'name=deploy comment="Aurora Store deployments" shell=/bin/bash create_home=true' -b
web1 | CHANGED => {
    "changed": true,
    "comment": "Aurora Store deployments",
    "create_home": true,
    "group": 1001,
    "home": "/home/deploy",
    "name": "deploy",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1001
}

This establishes deploy as the application's deployment user on the web servers. Check that it exists:

ansible webservers -a 'id deploy'

Repeat the creation: SUCCESS, no changes. To remove a user you would use state=absent (with remove=true to delete their home directory as well).

The deploy user created here is temporary: like everything done with ad hoc commands, it isn't recorded in the repository. Later on you will declare it in code (playbooks and, after that, the common role), which will be the source of truth.

  1. Rebooting servers

A reboot with command (-a reboot) would cut the connection, and Ansible would treat it as a failure. The ansible.builtin.reboot module does it properly: it reboots, waits for the server to respond again and checks that it's operational.

ansible web2 -m ansible.builtin.reboot -b
web2 | CHANGED => {
    "changed": true,
    "elapsed": 23,
    "rebooted": true
}

Caution: a reboot on all takes the store offline. Always do it by group or for specific hosts (--limit), and confirm first with --list-hosts. In Module 5 you will learn to reboot in batches, without downtime, using rolling deployments.

  1. Querying facts with setup

Facts are data that Ansible gathers from each server: operating system, memory, CPU, network interfaces, disks… The ansible.builtin.setup module returns them:

ansible db1 -m ansible.builtin.setup | less

That's hundreds of lines. Narrow it down with filter, which accepts wildcards:

ansible aurora -m ansible.builtin.setup -a 'filter=ansible_distribution*'
ansible aurora -m ansible.builtin.setup -a 'filter=ansible_memtotal_mb'
ansible webservers -m ansible.builtin.setup -a 'filter=ansible_default_ipv4'
db1 | SUCCESS => {
    "ansible_facts": {
        "ansible_memtotal_mb": 1967
    },
    "changed": false
}

You can already see the memory difference between db1 (2 GB) and the web servers (1 GB) that you defined in the Vagrantfile. How to use facts inside playbooks, cache them or create your own is covered in the "Variables and Facts" lesson in Module 3.

  1. Simulating changes: --check and --diff

Before changing anything in production, you will want to know what would change. Two options:

  • --check (-C): simulation mode. Modules that support it work out whether there would be changes, but don't apply them.
  • --diff (-D): shows the differences in files (before/after).

Combined, they're very powerful. Try changing the message in /etc/motd:

ansible web1 -m ansible.builtin.copy \
  -a 'content="Aurora Store server (web1). Authorized personnel only.\n" dest=/etc/motd' \
  -b --check --diff
--- before: /etc/motd
+++ after: /etc/motd
@@ -1 +1 @@
-Aurora Store server (web1). Restricted access.
+Aurora Store server (web1). Authorized personnel only.

web1 | CHANGED => {
    "changed": true,
    ...
}

It says CHANGED, but it's a prediction: check with ansible web1 -a 'cat /etc/motd' that the file hasn't been modified.

Watch out for command and shell in check mode: since they can't predict what an arbitrary command would do, in --check they don't run and show up as skipped. Don't rely on --check to validate anything that depends on them.

  1. Parallelism, compact output and background tasks

12.1 -f and -o

# Process up to 20 hosts at a time (overrides forks=10 in ansible.cfg)
ansible aurora -a 'uptime' -f 20

# One line per host: ideal for many machines or for filtering with grep
ansible aurora -a 'uptime' -o
web1 | CHANGED | rc=0 | (stdout)  10:42:01 up  2:30,  0 user,  load average: 0.00, 0.00, 0.00

With -f 1 hosts are processed one at a time: useful for actions that must not overlap in time.

12.2 Background tasks: -B and -P

A long-running task (upgrading every package, for example) can outlast the SSH connection's timeout. That's what asynchronous execution is for:

Option Meaning
-B <seconds> Maximum time the task may take (background)
-P <seconds> How often to check whether it has finished (poll). -P 0 = launch and don't wait
# Launch the upgrade on db1 and return immediately
ansible db1 -m ansible.builtin.apt -a 'upgrade=safe update_cache=true' -b -B 1800 -P 0
db1 | CHANGED => {
    "ansible_job_id": "j123456789012.12345",
    "started": 1,
    "finished": 0,
    ...
}

Then check its status with the returned identifier (with -b, because the task was launched as root):

ansible db1 -m ansible.builtin.async_status -a 'jid=j123456789012.12345' -b

When it finishes, finished is 1 and you will see the full result. Playbooks use the same mechanism with the async and poll keywords, which you will see when optimizing playbooks in Module 5.

  1. The key lesson: idempotency

Compare two ways of installing tree on the web servers:

# Option 1: shell command
ansible webservers -m ansible.builtin.shell -a 'apt-get install -y tree' -b

# Option 2: module
ansible webservers -m ansible.builtin.apt -a 'name=tree state=present' -b

Run each one twice and observe:

shell with apt-get apt module
1st run CHANGED CHANGED (or SUCCESS if option 1 already installed it)
2nd run CHANGED (a lie!) SUCCESS, changed: false
Does it reflect reality? No Yes
--check Skipped Predicts correctly
Uninstalling A different command state=absent

With the module, the colors mean something: green tells you the server was already the way you wanted it, and yellow that something was changed. With shell, everything is always yellow and you lose that information. When you manage hundreds of servers, knowing exactly what changed is the difference between a controlled operation and flying blind.

To leave the machines as they were, uninstall tree (it isn't part of Aurora's configuration):

ansible webservers -m ansible.builtin.apt -a 'name=tree state=absent' -b

Common Mistakes and Tips

  • Forgetting -b: errors such as Permission denied, Could not open lock file /var/lib/dpkg/lock-frontend or Failed to lock apt for exclusive operation. Add --become.
  • Using command with pipes or $VARIABLES: it fails or, worse, does something unexpected. Use shell or, better, the appropriate module.
  • Badly nested quotes: -a "content="hello" dest=/tmp/x" breaks. Use single quotes outside and double quotes inside.
  • state=latest without thinking: it upgrades the package on every run whenever a new version comes out, which can cause unplanned changes. In most cases, use present.
  • restarted as if it were a state: it always restarts. To make sure a service is running, use started.
  • Mass reboots: never reboot on all without --limit.
  • Relying on --check with command/shell: those tasks are skipped in the simulation.
  • Tip: before an ad hoc command that makes changes, first run --list-hosts, then --check --diff and finally the real run.

Exercises

Exercise 1: Quick report

Using ad hoc commands, get the following for all three servers: (a) the free space on /, one line per host, (b) the kernel version and (c) the Ubuntu version using facts.

Exercise 2: An idempotent notice file

On the database servers, create the file /etc/aurora-role with the contents database, owner root and permissions 0644. Check that the second run produces no changes, and use --check --diff to simulate what would happen if you changed the contents to database-primary.

Exercise 3: From shell to modules

A colleague uses this command to make sure chrony (a time service) is installed and running on every server:

ansible all -m ansible.builtin.shell -a 'apt-get install -y chrony && systemctl start chrony' -b

Rewrite it as two ad hoc commands using idempotent modules and explain what you gain.

Solutions

Exercise 1.

ansible aurora -m ansible.builtin.shell -a "df -h / | tail -1" -o   # (a) needs shell because of the pipe
ansible aurora -a 'uname -r' -o                                      # (b) command is enough
ansible aurora -m ansible.builtin.setup -a 'filter=ansible_distribution_version'  # (c)

In (c) each host returns "ansible_distribution_version": "24.04".

Exercise 2.

ansible dbservers -m ansible.builtin.copy \
  -a 'content="database\n" dest=/etc/aurora-role owner=root group=root mode=0644' -b
# Second run: SUCCESS, changed: false

ansible dbservers -m ansible.builtin.copy \
  -a 'content="database-primary\n" dest=/etc/aurora-role owner=root group=root mode=0644' -b --check --diff

The simulation shows -database / +database-primary and CHANGED, but the file still contains database.

Exercise 3.

ansible all -m ansible.builtin.apt -a 'name=chrony state=present' -b
ansible all -m ansible.builtin.service -a 'name=chrony state=started enabled=true' -b

What you gain: truthful change reporting (green if everything was already fine), compatibility with --check, the service also being enabled at boot (enabled=true), clear error messages for each step and no fragile dependencies on the shell.

Conclusion

You now know how to use ansible as an everyday administration tool: you know the complete syntax of ad hoc commands, when to prefer them over a playbook, the difference between command and shell and their risks, and you have managed files, packages (htop on every server), services, users (the deploy user on the web servers), reboots and facts. You have learned to simulate with --check --diff, control parallelism and launch long-running tasks in the background. Above all, you have seen in practice why idempotent modules are the foundation of Ansible. In the next lesson, Ansible Modules, you will take a step back to see the full picture: what exactly a module is, which are the most widely used ones in ansible.builtin, how to read their documentation with ansible-doc and how to interpret their return values.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved