`lineinfile` appends the same line again on every run
IntermediateTroubleshootingModules, Idempotency and Handlers
Answer
Likely causes → regexp does not match the line that line writes. For example, the regexp is ^PermitRootLogin yes, the line written is PermitRootLogin no, so the next run finds no match and appends again. Without regexp, the comparison is on the exact line, so differences in whitespace also cause duplicates.
Diagnose → grep -n PermitRootLogin /etc/ssh/sshd_config shows several copies.
Fix → The regexp must match both the old and the new form:
- ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?\s*PermitRootLogin\s'
line: PermitRootLogin no
validate: /usr/sbin/sshd -t -f %s
Then remove the existing duplicates once.
Prevent → For anything more than a line or two, template the whole file or use *.d/ drop-in files.
More on Modules, Idempotency and Handlers
`ERROR! The requested handler 'Restart nginx' was not found in either the main handlers list nor in the listening handlers list`BeginnerA handler named `restart {{ app_service }}` is never found when notified as `restart myapp`AdvancedA `command` task reports `changed` on every run, and the Molecule idempotence check failsBeginner`curl ... | tar xz` fails on the host but the `shell` task reports successIntermediate`lineinfile` with `backrefs: true` reports `ok` but the line was never addedIntermediateA `template` task reports `changed` and restarts the service on every runIntermediate