Interview Prep/Ansible/Ad-hoc Commands, Modules and Idempotency

How do you make a `command` or `shell` task idempotent?

IntermediateConceptAd-hoc Commands, Modules and Idempotency
Answer

Tell Ansible when the task has nothing to do, and when it actually changed something.

- name: Initialise the database once
  ansible.builtin.command: /opt/app/bin/init-db
  args:
    creates: /var/lib/app/.initialised

- name: Apply migrations
  ansible.builtin.command: /opt/app/bin/migrate
  register: mig
  changed_when: "'Applying' in mig.stdout"
  failed_when: mig.rc != 0

creates/removes skip the task if a path exists/does not exist. changed_when turns an always-changed task into an accurate report. Use when with a prior stat or read-only command for more complex guards.

All Ansible questions Roadmap: Ansible

More on Ad-hoc Commands, Modules and Idempotency