Ansible lineinfile - modify a line

I wanted to make sure the parameter is also set to the correct value, so I used this replace invocation:

replace:
  path: /etc/default/grub
  regexp: '^(GRUB_CMDLINE_LINUX=(?:(?![" ]{{ option | regex_escape }}=).)*)(?:[" ]{{ option | regex_escape }}=\S+)?(.*")$'
  replace: '\1 {{ option }}={{ value }}\2'
vars:
  option: audit
  value: 1

This works if the option wasn't present previously, if it was but had the wrong option (only changes the value then) and if the whole string was empty (but adds a space before the option then). Also, it uses regex_escape to correctly work with option names that contain dots and the likes, and you only have to specify them once.


You may try this:

- lineinfile:
    state: present
    dest: /etc/default/grub
    backrefs: yes
    regexp: '^(GRUB_CMDLINE_LINUX=(?!.* audit)\"[^\"]+)(\".*)'
    line: '\1 audit=1\2'

This will add audit=1 (with a leading space) just before closing double quote. It will not match without double quotes. And it tries to be idempotent: doesn't match lines that already have audit (with a leading space) after GRUB_CMDLINE_LINUX=.

I'd recommend to use sites like regex101 to test your regular expressions first (there's also a substitution mode there).
When you're satisfied with the result, proceed with the Ansible task.