Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Insert word in GRUB cmdline

Tags:

regex

ansible

I'd like to use Ansible's lineinfile or replace module in order to add the word splash to the cmdline in GRUB.

It should work for all the following examples:

Example 1:

  • Before: GRUB_CMDLINE_DEFAULT=""
  • After: GRUB_CMDLINE_DEFAULT="splash"

Example 2:

  • Before: GRUB_CMDLINE_DEFAULT="quiet"
  • After: GRUB_CMDLINE_DEFAULT="quiet splash"

Example 3:

  • Before: GRUB_CMDLINE_DEFAULT="quiet nomodeset"
  • After: GRUB_CMDLINE_DEFAULT="quiet nomodeset splash"

The post Ansible: insert a single word on an existing line in a file explained well how this could be done without quotes. However, I can't get it to insert the word within the quotes.

What is the required entry in the Ansible role or playbook in order to add the word splash to the cmdline as shown?

like image 751
Kalsan Avatar asked Mar 05 '23 02:03

Kalsan


2 Answers

You can do this without a shell output, with 2 lineinfiles modules.

In your example you're searching for splash:

- name: check if splash is configured in the boot command
  lineinfile:
    backup: true
    path: /etc/default/grub
    regexp: '^GRUB_CMDLINE_LINUX=".*splash'
    state: absent
  check_mode: true
  register: grub_cmdline_check
  changed_when: false

- name: insert splash if missing
  lineinfile:
    backrefs: true
    path: /etc/default/grub
    regexp: "^(GRUB_CMDLINE_LINUX=\".*)\"$"
    line: '\1 splash"'
  when: grub_cmdline_check.found == 0
  notify: update grub

The trick is to try to remove the line if we can find splash somewhere, but doing a check only check_mode: true. If the term was found (found > 0) then we don't need to update the line. If it's not found, it means we need to insert it. We append it at the end with the backrefs.

like image 117
marcaurele Avatar answered Mar 16 '23 04:03

marcaurele


Inspired by Adam's answer, I use this one to enable IOMMU:

- name: Enable IOMMU
  ansible.builtin.lineinfile:
    path: /etc/default/grub
    regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((:?(?!intel_iommu=on).)*?)"$'
    line: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 intel_iommu=on"'
    backup: true
    backrefs: true
  notify: update-grub

Please note I've had to set backrefs to true in order to \1 reference to work otherwise the captured group was not replaced.

Idempotency works fine as well.

EDIT: Please note this snippet only works with an Intel CPU and might to be updated to fit your platform.

like image 21
bgondy Avatar answered Mar 16 '23 03:03

bgondy