I am struggling below scenario:
In /etc/default/grub file, there is GRUB_CMDLINE_LINUX_DEFAULT stanza, I need to insert audit=1 at the end of the line if value is not there already (note that there is quote char at the end of line). If audit=0 is present change it to audit=1.
lineinfile ansible module does not work, especially with inserting before last quote (").
Original /etc/default/grub:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi="
Optional /etc/default/grub:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=0" # change audit=0 to audit=1
#OR:
#GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1" # audit=1 is already here, so no action needed
Desired /etc/default/grub:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1"
I created a file where the text is audit=0 and tried to replace it with audit=1
my file was: grubfile:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=0"
my playbook:
---
- name: read grub file
lineinfile:
dest: /home/myhome/grubfile.txt
regexp: '^(.*)audit=0(.*)$'
line: '\1audit=1\2'
backup: yes
backrefs: yes
Basically we play with regexp taking the audit=1 as the regexp and storing the rest of the string with backrefs the resulting file is:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1"
Edit: This code will add it even if doesn't exist, It will first modify if the audit=0 is present, then will check if audit=1 exists and if it doesn't exist will append the audit=1 to the beginning of the quotes :
---
- name:
lineinfile:
dest: /home/mypath/grubfile.txt
regexp: '^(.*)audit=1(.*)$'
state: absent
check_mode: yes
changed_when: false
register: auditexist
- name: if audit=0 write audit=1
lineinfile:
dest: /home/mypath/grubfile.txt
regexp: '^(.*)audit=0(.*)$'
line: '\1audit=1\2'
backup: yes
backrefs: yes
register: auditmodified
- name: appen
lineinfile:
dest: /home/ivan/grubfile.txt
regexp: '^(.*)GRUB_CMDLINE_LINUX_DEFAULT="(.*)$'
line: '\1GRUB_CMDLINE_LINUX_DEFAULT="audit=1 \2 '
backup: yes
backrefs: yes
when: not auditexist.found and not auditmodified.changed
result:
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="audit=1 rootfstype=xfs quiet splash acpi_osi="