Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible lineinfile - modify a line

I'm new to Ansible and trying to modify a line in /etc/default/grub to enable auditing.

I need to add audit=1 within the quotes somewhere on a line that looks like:

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap biosdevname=0 net.ifnames=0 rhgb quiet net.ifnames=0"

So far I've managed to delete the line and am only left with

net.ifnames=0, audit=1

when I use something like

lineinfile:
  state: present
  dest: /etc/default/grub
  backrefs: yes
  regexp: "net.ifnames=0"
  line: "\1 audit=1"

Can this be done?

like image 516
Jeff Bilbro Avatar asked Sep 30 '16 16:09

Jeff Bilbro


People also ask

Which of the following module is used to modify a single line in a file?

Ansible lineinfile module is helpful when you want to add, remove, modify a single line in a file. You can also use conditions to match the line before modifying or removing using the regular expressions. You can reuse and modify the matched line using the back reference parameter.

How do you modify a line in a file using Ansible?

To modify a line, you need to use the Ansible backrefs parameter along with the regexp parameter. This should be used with state=present. If the regexp does not match any line, then the file is not changed. If the regexp matches a line or multiple lines, then the last matched line will be replaced.

How do you uncomment a line in Ansible?

Comment Out & Uncomment Lines using Ansible In Ansible this can be achieved by using the \1 in replace to match ( … every character inside brackets… ) in regexp .


1 Answers

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.

like image 137
Konstantin Suvorov Avatar answered Sep 18 '22 15:09

Konstantin Suvorov