Interview Prep/Ansible/Modules, Idempotency and Handlers

`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.

All Ansible questions Roadmap: Ansible

More on Modules, Idempotency and Handlers