Skip to content

Instantly share code, notes, and snippets.

@jmpolom
Last active October 20, 2021 17:02
Show Gist options
  • Save jmpolom/9e4838b81428ab8d4942ea720a9530e6 to your computer and use it in GitHub Desktop.
Save jmpolom/9e4838b81428ab8d4942ea720a9530e6 to your computer and use it in GitHub Desktop.
Ansible lineinfile regex to edit Fedora GRUB_CMDLINE_LINUX and enable grub serial console
- name: test regex with lineinfile to edit default grub config
hosts: localhost
connection: local
gather_facts: no
vars:
ip_string: "ip=192.168.1.211::192.168.1.254:255.255.255.0:::"
tasks:
- name: edit GRUB_CMDLINE_LINUX
ansible.builtin.lineinfile:
backrefs: yes
backup: yes
path: grub
line: '\g<grub_cmdline_1> {{ item }}\g<grub_cmdline_2>'
regexp: '(?P<grub_cmdline_1>^GRUB_CMDLINE_LINUX=(?!.*?\b{{ item }})\"[^\"]*)(?P<grub_cmdline_2>\".*$)'
loop:
- "console=tty1"
- "console=ttyS0,115200n8"
- "console=ttyS1,115200n8"
- name: add GRUB_SERIAL_COMMAND
ansible.builtin.lineinfile:
backup: yes
path: grub
line: 'GRUB_SERIAL_COMMAND="serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1"'
regexp: '^GRUB_SERIAL_COMMAND=.*$'
- name: remove GRUB_TERMINAL_OUTPUT
ansible.builtin.lineinfile:
backup: yes
path: grub
state: absent
regexp: '^GRUB_TERMINAL_OUTPUT=.*'
- name: set GRUB_TERMINAL
ansible.builtin.lineinfile:
backup: yes
path: grub
line: 'GRUB_TERMINAL="console serial"'
regexp: '^GRUB_TERMINAL=\"console serial\"'
- name: edit GRUB_CMDLINE_LINUX to set ip argument if one does not exist yet
ansible.builtin.lineinfile:
backrefs: yes
backup: yes
path: grub
line: '\g<grub_cmdline_1> {{ ip_string }}\g<grub_cmdline_2>'
regexp: '(?P<grub_cmdline_1>^GRUB_CMDLINE_LINUX=(?!.*?ip=)\"[^\"]*)(?P<grub_cmdline_2>\".*?$)'
- name: edit GRUB_CMDLINE_LINUX to set ip argument if one does exist already but is not an exact match for the one required
ansible.builtin.lineinfile:
backrefs: yes
backup: yes
path: grub
line: '\g<grub_cmdline_1> {{ ip_string }}\g<grub_cmdline_2>'
regexp: '^(?P<grub_cmdline_1>GRUB_CMDLINE_LINUX=(?!.*?{{ ip_string }})\"[^\"]*?)\s?(?:ip=\S+)\s?(?P<grub_cmdline_2>[^\"]*\"$)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment