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
- Complete syntax of an ad hoc command
- Ad hoc or playbook: when to use each one
- Quick queries:
commandversusshell - Escalating privileges with
--become - Copying files
- Managing packages
- Managing services
- Managing users
- Rebooting servers
- Querying facts with
setup - Simulating changes:
--checkand--diff - Parallelism, compact output and background tasks
- The key lesson: idempotency
- Complete syntax of an ad hoc command
| 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"}' --becomeAlways 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.
- 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.
- Quick queries:
command versus shell
command versus shell3.1 The default module: command
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.00As 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 (*):
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/datawould 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
shellwithapt-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.
- Escalating privileges with
--become
--becomeMost 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.
- 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' -bcontent=: the file's contents (an alternative tosrc=, 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:
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.
- 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:
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.
- Managing services
ansible.builtin.service controls system services. Make sure cron is started and enabled at boot:
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:
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).
- 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' -bweb1 | 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:
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
deployuser 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, thecommonrole), which will be the source of truth.
- 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.
Caution: a reboot on
alltakes 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.
- Querying facts with
setup
setupFacts are data that Ansible gathers from each server: operating system, memory, CPU, network interfaces, disks… The ansible.builtin.setup module returns them:
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'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.
- Simulating changes:
--check and --diff
--check and --diffBefore 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
commandandshellin check mode: since they can't predict what an arbitrary command would do, in--checkthey don't run and show up asskipped. Don't rely on--checkto validate anything that depends on them.
- 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' -oWith -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 0Then check its status with the returned identifier (with -b, because the task was launched as root):
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.
- 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' -bRun 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):
Common Mistakes and Tips
- Forgetting
-b: errors such asPermission denied,Could not open lock file /var/lib/dpkg/lock-frontendorFailed to lock apt for exclusive operation. Add--become. - Using
commandwith pipes or$VARIABLES: it fails or, worse, does something unexpected. Useshellor, better, the appropriate module. - Badly nested quotes:
-a "content="hello" dest=/tmp/x"breaks. Use single quotes outside and double quotes inside. state=latestwithout thinking: it upgrades the package on every run whenever a new version comes out, which can cause unplanned changes. In most cases, usepresent.restartedas if it were a state: it always restarts. To make sure a service is running, usestarted.- Mass reboots: never
rebootonallwithout--limit. - Relying on
--checkwithcommand/shell: those tasks are skipped in the simulation. - Tip: before an ad hoc command that makes changes, first run
--list-hosts, then--check --diffand 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:
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 --diffThe 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' -bWhat 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
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
