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.
More on Ad-hoc Commands, Modules and Idempotency
What is an ad-hoc command and what is its syntax?BeginnerWhat does `ansible all -m ping` actually test?BeginnerGive practical use cases for ad-hoc commands.IntermediateWhat is the difference between the `command` and `shell` modules?BeginnerCompare `raw`, `command`, `shell` and `script`.IntermediateWhy prefer a dedicated module over `shell`/`command`?Beginner