Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Broken idempotence and performance tuning: creates, changed_when, pipelining, forks

18 min read
Improve this page

Logo Ansible

An idempotent playbook shows changed=0 on its second run: it noticed that the system was already in the wanted state and touched nothing. When changed=N comes back on every run, the recap can no longer tell a real change from a task that replays for nothing, and a service may be restarted for no reason. This page covers three common causes (shell without creates:, a read-only command without changed_when:, lineinfile without regexp:), shows a reliable idempotence test for CI, then presents the SSH settings that shorten a playbook (pipelining, forks, ControlPersist) and how to measure their effect on your own fleet.

What you will learn

  • Recognise the modules that are not idempotent by default (command, shell, raw, script).
  • Make a command idempotent with creates: or removes:.
  • Tell changed_when: (what the task reports) from failed_when: (what counts as a failure).
  • Fix a lineinfile that duplicates its lines, with regexp:.
  • Write an idempotence test that really fails when it should.
  • Measure a playbook with profile_tasks and time, then tune pipelining, forks, ControlPersist and the fact cache.

Prerequisites

  • Have read Ansible verbosity (in French).
  • Know the shell, command and lineinfile modules.
  • For the measuring callbacks, have the ansible.posix collection, which a bare ansible-core installation does not include: ansible-galaxy collection install ansible.posix.

Which modules are not idempotent by default?

The command, shell, raw and script modules run whatever they are given without knowing anything about the state of the system: Ansible cannot guess whether the command had an effect, so it reports it as changed on every run. Modules that describe a state, such as copy, template, lineinfile, file, dnf or systemd, compare the wanted state with the real one and report a change only if they made one.

ModuleWhy it is not idempotentFix
commandIt runs the command every timecreates:, removes: or changed_when:
shellSame behaviour, through a shellcreates:, removes: or changed_when:
rawIt goes through SSH without Python, so it has no notion of stateReserved for bootstrapping a machine; afterwards, use a real module
scriptIt copies and runs a local scriptcreates: or removes:

The details of these four modules (when to prefer them, their risks) are in raw, command, shell, script (in French).

How do you make a shell task idempotent with creates:?

Here is a task that drops a marker file:

- name: Create the run marker
ansible.builtin.shell: "echo lab > /tmp/marker"

On every run, the recap shows changed=1, because nothing tells Ansible that the work is already done. The creates: parameter settles the question: if the given path already exists, the task is not run and ends up ok.

- name: Create the run marker
ansible.builtin.shell: "echo lab > /tmp/marker"
args:
creates: /tmp/marker

On the first run, changed=1; on the second, the file exists and the task is skipped. The opposite parameter, removes:, skips the task when the path does not exist, which suits a command that deletes something:

- name: Purge the old cache
ansible.builtin.command:
cmd: rm -rf /tmp/old-cache
removes: /tmp/old-cache

This example shows the mechanism, but it is not good practice: deleting a directory does not need a command, since the file module can do it and is idempotent by itself.

- name: Purge the old cache
ansible.builtin.file:
path: /tmp/old-cache
state: absent

Keep creates: and removes: for the cases where no module exists for the operation.

What about a command that only reads?

A read command changes nothing, yet command still reports it as changed.

- name: Read the git version
ansible.builtin.command: git --version
register: git_version

The changed_when: keyword replaces the module's change verdict with an expression you write. It acts on what the task reports, not on what it runs: the command is launched in every case. For a read, the answer is false.

- name: Read the git version
ansible.builtin.command: git --version
register: git_version
changed_when: false

Without the keyword, the task shows changed on every run; with it, the task shows ok, and the recap counts no change:

TASK [Read the git version] ****************************************************
ok: [cible]
PLAY RECAP *********************************************************************
cible : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

The task then ends up ok on every run, and a real change elsewhere in the playbook stays visible in the recap.

When should you use changed_when: with an expression?

Some commands act without telling Ansible, but their output says whether they did something. You then read that output to decide the verdict. git init gives an example: it prints Initialized empty Git repository the first time, and Reinitialized existing Git repository when the repository already exists. In real life you would rather write creates: /tmp/depot/.git; the expression on the output is used here to show the mechanism:

- name: Initialise the repository
ansible.builtin.command: git init /tmp/depot
register: init
changed_when: "'Reinitialized' not in init.stdout"

On the first run the task is changed, on the second it is ok, even though the command did run again (init.stdout is Reinitialized existing Git repository in /tmp/depot/.git/).

Change and failure are two separate questions

changed_when: says nothing about whether the task succeeded. To decide that a result is a failure, you need failed_when:. A health check that answers badly must not appear as "modified": it must make the task fail, and it modifies nothing.

- name: Check the application health
ansible.builtin.uri:
url: "http://localhost:8080/health"
return_content: true
register: health
failed_when: "'OK' not in health.content"

If the server answers 200 with KO in the body, the task fails and the recap shows failed=1, with no changed at all ("changed": false in the detail):

fatal: [cible]: FAILED! => {"changed": false, "content": "KO\n", ..., "failed_when_result": true, "msg": "OK (3 bytes)", "status": 200, ...}
PLAY RECAP *********************************************************************
cible : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

The msg field repeats the reason phrase of HTTP status 200, not the response body: content is what holds KO. With OK in the body, the task ends up ok.

Without failed_when:, this check would already fail if the server answered with an HTTP code outside the expected range, but a 200 response containing anything other than OK would pass. The success criterion is the one you write. The page failed_when and changed_when (in French) details both keywords, including how to combine them on a single task.

Why does lineinfile need regexp:?

Without regexp:, lineinfile only looks for the exact line given in line:. If that line is missing, it adds it, even if an earlier version of the same directive is present.

- name: Tune myapp.cfg
ansible.builtin.lineinfile:
path: /etc/myapp.cfg
line: "max_connections = 100"
state: present
create: true

The first run creates the line. If you then change line: to max_connections = 200, the second run adds the new line without touching the old one, and the file contains both:

max_connections = 100
max_connections = 200

Depending on the application, either the first or the last occurrence wins, which makes the behaviour unpredictable. With regexp:, the module finds the existing line and replaces it. The file lives under /etc, so the task runs with become: true, and it sets owner, group and permissions instead of inheriting them:

- name: Tune myapp.cfg
become: true
ansible.builtin.lineinfile:
path: /etc/myapp.cfg
regexp: '^max_connections\s*='
line: "max_connections = 200"
state: present
create: true
owner: root
group: root
mode: "0644"

Set regexp: from the very first write of the directive: that is what lets you change it later without a duplicate. ansible-lint does not flag its absence; only a review catches it.

How do you test idempotence in CI?

The test consists in running the playbook twice on a throwaway target and requiring that the second run changes nothing. Both runs must also succeed: a playbook that fails on its second pass is not idempotent, even if no changed shows up.

The trap in this kind of script is tee. In a shell pipeline, the exit code is that of the last command, hence that of tee, which always succeeds. Without set -o pipefail, a failing ansible-playbook goes unnoticed, and searching the log only for changed=[1-9] detects nothing if the play stopped before changing anything.

#!/usr/bin/env bash
set -euo pipefail
playbook="${1:?usage: $0 playbook.yml}"
log="$(mktemp)"
trap 'rm -f "$log"' EXIT
export ANSIBLE_NOCOLOR=1
# First run: it may modify the target, but it must succeed.
ansible-playbook "$playbook"
# Second run: it must succeed too, and change nothing.
ansible-playbook "$playbook" | tee "$log"
if grep -Eq '(changed|failed|unreachable)=[1-9]' "$log"; then
echo "Idempotence KO: the second run changed or failed" >&2
exit 1
fi
echo "Idempotence OK"

Run on four playbooks, this script behaves as follows:

PlaybookExit codeOutput
idempotent (shell with creates:)0changed=1 then changed=0, Idempotence OK
not idempotent (shell without creates:)1changed=1 on both runs, Idempotence KO: the second run changed or failed
failure on the first run2failed=1, the script stops before the second run
failure on the second run2failed=0 then failed=1, no Idempotence OK

set -e stops the script if the first run fails. pipefail propagates the exit code of ansible-playbook through the tee, so a failing second run also stops the script. The search in the recap (PLAY RECAP) covers the three counters that must stay at zero, and ANSIBLE_NOCOLOR=1 keeps colour sequences from slipping into the log.

This test is not the --check --diff mode. The latter simulates a run without modifying anything and shows what would change: it is used to detect drift on an existing system, or to review a change before applying it. It does not replace the idempotence test, for two reasons. command and shell tasks are skipped in check mode (skipping), except with creates: or removes:: the condition is then evaluated without running the command, and the task reports changed if it would run. Tasks that depend on the output of a skipped command therefore cannot be evaluated correctly. Idempotence can only be verified by really applying, hence the throwaway target.

Molecule chains the same check in its idempotence step; the full cycle is in TDD cycle with Molecule (in French).

How do you measure before optimising?

A performance setting is judged on a measurement, not on a general rule: the gain depends on the number of hosts, the network latency and the number of tasks. Start with a baseline, by enabling the timing callbacks in ansible.cfg:

[defaults]
callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer

profile_tasks ranks the tasks by duration at the end of the playbook, which shows where the time goes (the callback is introduced in Ansible verbosity, in French). For the total duration, run time ansible-playbook playbook.yml and note the result. Repeat the measurement after each setting, one change at a time, on the same inventory and under the same conditions: several successive runs give an idea of the spread.

Which SSH settings speed up a playbook?

Three connection and parallelism settings complement each other, and the fact cache adds a fourth. They do not all have the same effect depending on the context, which is why the previous measurement matters.

pipelining

Without pipelining, Ansible prepares each module on the target in several operations (creating a temporary directory, transferring the file, running it). With pipelining = True, the module is sent over the standard input of the Python interpreter: there are fewer network operations per task. The default value is False.

[ssh_connection]
pipelining = True

forks

forks sets the number of hosts handled in parallel. The default value is 5 (ansible-config list, entry DEFAULT_FORKS).

[defaults]
forks = 20

Raising this value only helps if you have more hosts than forks: with three machines, 5 is already enough. A very high value uses memory and file descriptors on the control node, and multiplies simultaneous SSH connections. Go up in steps while watching the machine that runs Ansible. The other parallelism levers (serial, throttle, strategy) are in Parallelism and strategies (in French).

ControlMaster and ControlPersist

OpenSSH can keep a connection open and reuse it for the following tasks, which avoids repeating the negotiation each time. The point to know: Ansible's ssh_args option already defaults to -C -o ControlMaster=auto -o ControlPersist=60s (ansible-doc -t connection ansible.builtin.ssh). This setting is therefore active without doing anything. Changing it only makes sense if 60 seconds are too short, for instance when long tasks separate two connections to the same host.

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=300s

This line replaces the default value entirely: so repeat every option you want to keep.

The fact cache

Facts are gathered at the start of each play. On a stable fleet, they change little from one run to the next, and they can be kept between two runs. With gathering = smart, Ansible gathers them only if they are not already cached or if the cache has expired.

[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible-fact-cache
fact_caching_timeout = 7200

The first run fills the cache: measure from the second one. A stale cache makes tasks work on outdated facts, hence the expiry delay (here 7200 seconds, that is two hours).

A starter ansible.cfg

The previous settings come together in a single file, to adjust after measuring:

[defaults]
forks = 20
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible-fact-cache
fact_caching_timeout = 7200
callback_result_format = yaml
callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer
[ssh_connection]
pipelining = True

The two callbacks are those of the measuring section, and callback_result_format = yaml makes the task output readable over several lines instead of compact JSON. The details of the sections and of the loading order are in the ansible.cfg file.

Put it into practice

A recap that shows changed=N on every run is diagnosed by comparing the first two runs, not by rereading the YAML. The lab reproduces the three cases described above and has you fix them one by one: creates: on a shell, changed_when: on a read command, regexp: on a lineinfile that duplicates. It then has you take a baseline measurement with profile_tasks, before tuning pipelining and forks (ControlPersist is already active by default). The challenge takes a complete playbook, and the validation compares the second run with the first: changed=0 is the success criterion.

Key takeaways

  • command, shell, raw and script report changed on every run unless you give them a condition.
  • creates: and removes: make a command idempotent by testing whether a path exists; a state module is still preferable when one exists.
  • changed_when: decides what the task reports, failed_when: what counts as a failure; a read command takes changed_when: false.
  • lineinfile takes a regexp: from the first write, otherwise a later change duplicates the line.
  • An idempotence test requires both runs to succeed (set -euo pipefail) and the second to report no changed, no failed and no unreachable.
  • --check --diff detects drift without applying anything; it does not replace this test.
  • The pipelining, forks and ControlPersist settings are judged by a measurement before and after (time ansible-playbook, profile_tasks); ControlPersist=60s is already the default setting.
  • The fact cache (gathering = smart with fact_caching) only pays off from the second run, and its expiry delay keeps you from working on outdated facts.

Knowledge check

Check that the essentials of this lesson are in place. The questions only cover what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer