LOGBOOK

HELP

Quiz Entry - updated: 2026.11.12

What does ansible.builtin.lineinfile guarantee, and how do you use it to change an existing setting rather than append a duplicate?

It guarantees that one line is (or is not) in a file. With only line: it appends the line if it's missing; with regexp: it replaces the last line that matches, so a setting is changed in place instead of added twice.

- name: Add a line of text to a file
  ansible.builtin.lineinfile:
    path: /path/to/file
    line: 'Add this line to the file'
    state: present

That is enough for a line that must simply exist. For a setting, the old value is already in the file in some form, and appending would leave two conflicting lines:

- name: Disable root login over SSH
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^#?PermitRootLogin'
    line: 'PermitRootLogin no'

regexp finds the existing line (here also a commented-out one) and replaces it with line. If nothing matches, line is added at the end, or where insertafter/insertbefore says. For idempotence the pattern must match the line both before and after the change; otherwise every run appends another copy. state: absent with a regexp removes all matching lines.

Go deeper:

From Quiz: ITIA / Ansible: Managing Files and Jinja2 Templates | Updated: Nov 12, 2026