Interview Prep/Ansible/Modules, Idempotency and Handlers

A `command` task reports `changed` on every run, and the Molecule idempotence check fails

BeginnerTroubleshootingModules, Idempotency and Handlers
Answer

Likely causes → command and shell cannot know whether they changed anything, so they always report changed: true.

Fix → Choose the option that fits:

# 1. Run only if an artifact is missing
- ansible.builtin.command: /opt/app/bin/init-db
  args:
    creates: /var/lib/app/.initialised

# 2. Read-only commands
- ansible.builtin.command: /opt/app/bin/app --version
  register: v
  changed_when: false

# 3. Decide from the output
- ansible.builtin.command: /opt/app/bin/migrate
  register: m
  changed_when: "'No migrations to apply' not in m.stdout"

Prevent → Prefer a real module when one exists. ansible-lint rule no-changed-when flags these tasks.

All Ansible questions Roadmap: Ansible

More on Modules, Idempotency and Handlers