Introduction

Ansible, the automation tool of choice for many IT professionals, allows users to automate tasks, manage configurations, and deploy software with ease and efficiency. However, the reliability and predictability of Ansible playbooks depend on how well tasks report changes. In this article, we will explore Ansible Error 301, "no-changed-when," in [Ansible-Lint](/articles/ansible-lint) which emphasizes the importance of ensuring that tasks return changes to results or conditions. We'll discuss the best practices for handling task outputs, improving playbook reliability, and preventing unexpected behavior.

The Problem: Tasks Not Reflecting Changes

Ansible Error 301, "no-changed-when," checks whether tasks within a playbook report changes to results or conditions. Tasks that do not naturally detect whether a change has occurred should use the changed_when clause to define under what conditions they should be considered "changed." This is particularly important for tasks that read or execute arbitrary commands, such as those using the shell or command modules.

Problematic Code Example:

``yaml

---

  • name: Example playbook

hosts: all

tasks:

- name: Does not handle any output or return codes

ansible.builtin.command: cat {{ my_file | quote }} # <- Does not handle the command output.

`

In the problematic code above, the task does not handle the output of the cat command or the return codes, making it difficult to determine if the task resulted in any changes.

Output:

`bash

WARNING Listing 1 violation(s) that are fatal

no-changed-when: Commands should not change things if nothing needs doing.

301.yml:5 Task/Handler: Does not handle any output or return codes

Read documentation for instructions on how to ignore specific rule violations.

Rule Violation Summary

count tag profile rule associated tags

1 no-changed-when shared command-shell, idempotency

Failed: 1 failure(s), 0 warning(s) on 1 files. Last profile that met the validation criteria was 'safety'. Rating: 3/5 star

`

Correcting Tasks to Reflect Changes

To address Ansible Error 301 and ensure tasks properly reflect changes, you should use the changed_when clause or other relevant arguments. Here's the corrected code:

`yaml

---

  • name: Example playbook

hosts: all

tasks:

- name: Handle shell output with return code

ansible.builtin.command: cat {{ my_file | quote }}

register: my_output # <- Registers the command output.

changed_when: my_output.rc != 0 # <- Uses the return code to define when the task has changed.

`

In the corrected code, the task registers the command output and uses the changed_when` clause to specify under what conditions the task should be considered "changed."

Benefits of Tasks Reflecting Changes

1. Reliability: Ensuring that tasks reflect changes improves the reliability and predictability of your Ansible playb