Ansible Reports Every command and shell Task as Changed Unless creates or changed_when Decides
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
- DevOps and Infrastructure as Code MOC - hub for automation notes.
- Ansible Handlers Notified in a Failed Run Never Fire, and the Re-run Sees Nothing to Change - what depends on a task reporting its change correctly.
- Idempotent Scripts Check the Current State Before Changing It - the same check-before-acting rule in Bash.
- An Ansible replace Task That Matches Nothing Reports ok, So Assert the End State - the opposite problem: a task that reports no change when it should have acted.
- Ansible documentation: command module -
creates,removesand why the module always reports a change. - Ansible documentation: Defining "changed" -
changed_when.