How do you make an Ansible task idempotent?
IntermediateProductionPatching, Automation & Golden Images
Answer
Use modules that describe desired state (package, template, lineinfile, systemd, user) instead of shell/command. When you must run a command, guard it with creates:/removes: or changed_when:/when:.
- name: Initialize app DB once
ansible.builtin.command: /opt/app/bin/init-db
args:
creates: /var/lib/app/.initialized
Run twice; the second run must report changed=0.
More on Patching, Automation & Golden Images
What does a good Linux patching strategy look like?BeginnerIn-place patching vs immutable image replacement: which do you prefer?IntermediateHow do you know whether a server needs a reboot after patching?BeginnerHow do you configure automatic security updates?BeginnerWhat is kernel live patching?IntermediateHow do you roll kernel updates across a 200-node fleet safely?Advanced