Ansible Reports Every command and shell Task as Changed Unless creates or changed_when Decides

In progress Ansible

Ansible's state modules (apt, file, template) compare the target with the desired state and report changed only when they act. The command and shell modules can't know what a command did, so they run it every time and report changed every time. A playbook full of them is never quiet, restarts services on every run through their handlers, and hides real drift among false changes.

Skip the Command When Its Result Already Exists

When a command produces a file, creates makes the task skip once the file is there (removes is the reverse):

- name: Generate the default containerd configuration
  ansible.builtin.shell: containerd config default > /etc/containerd/config.toml
  args:
    creates: /etc/containerd/config.toml

The task is then ok on every run after the first, like a real module.

Let the Result Decide with changed_when

changed_when takes an expression over the registered result. It suits commands that are safe to run each time and say whether they acted:

- name: Check the cluster is reachable
  ansible.builtin.command: kubectl --request-timeout=5s get nodes
  changed_when: false          # read-only: never a change

For a command that edits a file, compare the file before and after rather than guessing from the output:

- ansible.builtin.stat: { path: /etc/containerd/config.toml, checksum_algorithm: sha256 }
  register: before
- ansible.builtin.command: nvidia-ctk runtime configure --runtime=containerd --set-as-default
  changed_when: false          # the stat below decides
- ansible.builtin.stat: { path: /etc/containerd/config.toml, checksum_algorithm: sha256 }
  register: after
  changed_when: before.stat.checksum != after.stat.checksum
  notify: Restart containerd

References