An Ansible replace Task That Matches Nothing Reports ok, So Assert the End State

In progress Ansible

ansible.builtin.replace describes a state of the form "no line matches this pattern". When the pattern is absent, that state already holds, so the task reports ok and moves on. A file that never contained the pattern at all satisfies it just as well as a file that was already fixed. The task can't tell "already done" from "nothing to do here", and neither can the person reading the run.

The Symptom

A playbook sets containerd's cgroup driver with:

- name: Configure SystemdCgroup in containerd config
  ansible.builtin.replace:
    path: /etc/containerd/config.toml
    regexp: 'SystemdCgroup = false'
    replace: 'SystemdCgroup = true'

On a fresh Debian node the run is green and the task says ok. The file has no SystemdCgroup line at all (see Debian's containerd Package Ships a Config Stub Without SystemdCgroup), so the setting the play exists for was never applied. Nothing failed, nothing changed, and the play reports success.

Why ok Is Not Evidence

Task result What it proves
changed The pattern was there and was rewritten.
ok The pattern is not there now. It does not prove the wanted text is there.

lineinfile with regexp has a similar trap: with state: present it adds the line when nothing matches, which is safer, but in a TOML or INI file it may add it in the wrong section.

Fix: Check the State You Actually Want

Add a task that fails unless the wanted text is present:

- name: Assert containerd uses the systemd cgroup driver
  ansible.builtin.command: grep -q 'SystemdCgroup = true' /etc/containerd/config.toml
  changed_when: false   # read-only check, never a change

A non-zero exit fails the play, so the silent no-op becomes a loud error. ansible.builtin.assert does the same over registered variables or facts.

References