Home > OS >  Add options into string via Ansible (lineinfile)
Add options into string via Ansible (lineinfile)

Time:03-20

I need to add net.ifnames=0 biosdevname=0 to GRUB_CMDLINE_LINUX line in /etc/default/grub but only if both of them is not present in this line.

GRUB_CMDLINE_LINUX="crashkernel=auto resume=/dev/mapper/cl-swap rd.lvm.lv=cl/root rd.lvm.lv=cl/swap"

Here I use lifeinfile module:

 - name: Change /etc/defaut/grub
   lineinfile:
     dest: /etc/default/grub
     regexp: '(^GRUB_CMDLINE_LINUX=". ?)"'
     state: present
     line: '\1 net.ifnames=0 biosdevname=0"'
     backrefs: yes

If only net.ifnames=0 therefore need to add biosdevname=0 only, if only biosdevname=0, then add net.ifnames=0. How can I achieve that?

I've try to use something like this

(GRUB_CMDLINE_LINUX=(?!.*((net.ifnames=0)|(biosdevname=0))).*[^\"])

but I totally don't realize how can I add only net.ifnames=0 or only biosdevname=0 based on conditions if one of them exist in the line.

CodePudding user response:

either net.ifnames=0 and biosdevname=0 could be present more times (more lines) in the file, so 3 steps:

- name: put off net.ifnames=0 from the line GRUB..
  lineinfile:
    dest: /etc/defaut/grub
    regexp: '(^GRUB_CMDLINE_LINUX=". ?) *net\.ifnames=0 *(.*)'
    state: present
    line: '\1 \2'
    backrefs: yes
- name: put off biosdevname=0 from the line GRUB..
  lineinfile:
    dest: /etc/defaut/grub
    regexp: '(^GRUB_CMDLINE_LINUX=". ?) *biosdevname=0 *(.*)'
    state: present
    line: '\1 \2'
    backrefs: yes

- name: add net.ifnames=0 biosdevname=0 to end of line GRUB...
  lineinfile:
    dest: /etc/defaut/grub
    regexp: '(^GRUB_CMDLINE_LINUX=". ?) *"'
    state: present
    line: '\1 net.ifnames=0 biosdevname=0"'
    backrefs: yes

either net.ifnames=0 and biosdevname=0 could be present only one time (single line) in the file, so 2 steps:

- name: replace all net.ifnames=0 biosdevname=0 by ' '
  replace:
    dest: /etc/defaut/grub
    regexp: ' *net\.ifnames=0 *| *biosdevname=0 *'
    replace: ' '

- name: add net.ifnames=0 biosdevname=0 to end of line GRUB...
  lineinfile:
    dest: /etc/defaut/grub
    regexp: '(^GRUB_CMDLINE_LINUX=". ?) *"'
    state: present
    line: '\1 net.ifnames=0 biosdevname=0"'
    backrefs: yes
  • Related