Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 29 ยท Core Concepts

Modules and Idempotence

Understand why Ansible modules beat shell commands: ok, changed and failed states, command vs shell vs raw, creates and removes, changed_when, failed_when and check mode.

Every task in Ansible calls a module, a small program that knows how to do one kind of job on a managed node: install a package, copy a file, manage a user, restart a service. Modules are what make Ansible more than "SSH in a loop". A good module looks at the machine, decides whether anything must change, changes only that, and reports exactly what happened.

Sometimes there is no module for the job and you reach for a shell command. That is allowed, but then you take on the work the module would have done for you: checking the current state and telling Ansible whether anything changed. This lesson explains how results are reported, how command, shell and raw differ, and how creates, removes, changed_when and failed_when make plain commands behave. The YAML shown is read-only; the stand-ins compare modules with scripts over repeated runs and evaluate changed_when rules.

Why a module beats a shell command

Compare two ways to make sure a user exists:

YAML
# The module way
- name: Create the deploy user
  ansible.builtin.user:
    name: deploy
    shell: /bin/bash

# The shell way
- name: Create the deploy user
  ansible.builtin.shell: useradd -m -s /bin/bash deploy

Run each one twice. The module notices the user exists and reports ok. The shell command fails the second time ("user already exists"), or, if it did not fail, it would report changed anyway, because Ansible cannot read the mind of a command.

Modules give you:

  • Idempotence. They check first and act only when needed.
  • Accurate reporting. ok versus changed is true, so the recap means something.
  • Check mode and diff support. Many modules can predict their changes and show file differences.
  • Validation and clear errors. Wrong arguments are rejected with a message, rather than half-working.
  • Portability. ansible.builtin.package works on apt, dnf and others; a shell line is tied to one distribution.

Before writing a shell task, search for a module. ansible-doc -l lists all modules you have installed, and ansible-doc ansible.builtin.user shows the documentation of one, with every argument and examples, offline.

The three results: ok, changed, failed

Every task result for a host ends up in one of a few states:

flowchart TD
    S["Task runs on a host"] --> F{"Error?"}
    F -- yes --> X["failed<br/>(host is dropped from the play)"]
    F -- no --> C{"Did it change<br/>the machine?"}
    C -- yes --> CH["changed"]
    C -- no --> OK["ok"]
    S --> SK["skipped<br/>(a when: condition was false)"]

A task ends as ok, changed, failed or skipped, and the recap counts each state.

Behind the scenes a module returns a dictionary, JSON on the wire. Keys such as changed, failed, msg and, for commands, rc, stdout and stderr are standard. You can capture a result in a variable with register and look at it with the debug module; the next chapter, Variables, Facts and Precedence, covers that fully.

command, shell, raw and script

When there is truly no module, four modules run programs, each with a different level of magic:

Module Runs through Pipes, &&, $VAR Needs Python on target
ansible.builtin.command Directly, no shell No Yes
ansible.builtin.shell /bin/sh Yes Yes
ansible.builtin.raw SSH directly, no module Yes No
ansible.builtin.script Copies a local script, runs it Whatever the script does Yes (to copy)

Guidance:

  • Use command by default. Because no shell interprets the line, you cannot accidentally inject or mangle it.
  • Use shell only when you need shell features such as a pipe.
  • Use raw for bootstrapping, for example installing Python on a fresh machine or configuring a device where Python cannot run. It has no idempotence at all.
  • Use script when you already have a script on the control node and want to run it remotely.
YAML
- name: Count nginx processes
  ansible.builtin.shell: ps aux | grep -c '[n]ginx'
  register: nginx_count
  changed_when: false

Making commands idempotent: creates and removes

command, shell and script accept creates and removes, which turn a blind command into a conditional one:

YAML
- name: Build the tool only once
  ansible.builtin.command: make install
  args:
    chdir: /opt/tool-src
    creates: /usr/local/bin/tool

- name: Remove the lock file if it exists
  ansible.builtin.command: rm /var/run/app.lock
  args:
    removes: /var/run/app.lock

With creates, the command is skipped when the given path already exists (the module reports ok, with a message saying it was skipped). With removes, the command is skipped when the path does not exist. Both give you the "check first, then act" loop that real modules have, using a file as the sign that the work was done.

Telling Ansible the truth: changed_when and failed_when

By default, a command task is changed whenever it runs, and failed when its exit code is not 0. Two keywords let you replace both rules with your own expressions, which see the registered result:

YAML
- name: Read the app version (never a change)
  ansible.builtin.command: /opt/app/bin/app --version
  register: app_version
  changed_when: false

- name: Run database migrations
  ansible.builtin.command: /opt/app/bin/migrate
  register: migrate
  changed_when: "'Applied' in migrate.stdout"
  failed_when: migrate.rc not in [0, 2]
  • changed_when: false is the standard way to mark pure read-only commands, so they never pollute the recap.
  • changed_when: "'Applied' in migrate.stdout" says that the task changed something only when the output mentions it.
  • failed_when: migrate.rc not in [0, 2] treats exit code 2 as acceptable. When you set failed_when, it takes over the decision from the default "non-zero exit code means failure".

Quote an expression that contains a colon, quotes or braces, as above, or YAML may misread it.

Check mode and modules

Modules declare how well they support --check. File, package and service modules typically predict their changes accurately. A plain command or shell cannot predict anything, so in check mode they are skipped, unless you used creates or removes, which let Ansible work out whether the command would run. You can override per task:

YAML
- name: Always run this read-only query, even in check mode
  ansible.builtin.command: cat /etc/os-release
  check_mode: false
  changed_when: false

check_mode: false makes the task run for real even during --check. Use it only for harmless, read-only commands whose output later tasks need.

Stand-in: module versus script over repeated runs

This program applies the same goal to a pretend server three times, once with a "script" that blindly does each step and once with module-style functions that check first. Then it compares the damage and the reports.

JS Idempotent module versus naive script

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

No output.

After three runs the script has added the same line three times and logged two errors, while the module version stopped at one line and reported ok on runs two and three. That difference is the whole reason Ansible exists.

Stand-in: deciding changed and failed

Here is a small evaluator for changed_when and failed_when. A pretend command returns an exit code and some output. The default rules and the custom rules are written as functions, like the expressions in the YAML above.

JS Default rules versus changed_when and failed_when

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

No output.

With the default rules, a harmless version query counts as changed and exit code 2 counts as a failure. With the custom rules, the query is ok, "nothing to do" is ok, only real migrations are changed, and only unexpected exit codes fail. Modeling your commands this way keeps the recap honest. Stand-ins aside, the real keywords have access to the whole registered result, not only the fields shown here.

The next lesson group moves from single tasks to data: Variables, Facts and Precedence.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a module such as ansible.builtin.user usually beat shell: useradd ...?

    Modules are idempotent and report state honestly. A shell command repeats its action and Ansible can only guess whether it changed anything.
  2. 2. Which module should you choose to run a command that needs a pipe?

    command does not use a shell, so pipes are not interpreted. shell passes the line to /bin/sh, which supports them.
  3. 3. What does creates: /usr/local/bin/tool do on a command task?

    creates makes the command conditional: if the path exists, the work is assumed done and the command is not run. removes does the opposite check.
  4. 4. A read-only command (such as app --version) shows up as changed in every recap. What fixes this?

    changed_when: false tells Ansible this task never changes the system, so it is reported as ok.
  5. 5. When is the raw module the right choice?

    raw runs a command over SSH without using a module, so it works without Python on the target. It offers no idempotence or reporting.

Summary

  • A module checks the real state, changes only what differs and reports ok, changed, failed or skipped truthfully.
  • Prefer a real module to a shell command; look for one with ansible-doc -l and read its docs with ansible-doc <name>.
  • command runs without a shell, shell uses /bin/sh, raw needs no Python (for bootstrapping), and script runs a local script remotely.
  • creates and removes make a command conditional on a path, giving it a basic idempotence.
  • changed_when and failed_when replace the default rules (every command changes; non-zero exit fails) with your own expressions.
  • Command-style modules cannot predict their effect in check mode and are skipped unless creates or removes decide it; check_mode: false forces a read-only task to run.

Next: Variables, Facts and Precedence