# platform = multi_platform_debian,multi_platform_fedora,multi_platform_ol,multi_platform_rhel,multi_platform_rhv,multi_platform_sle,multi_platform_slmicro,multi_platform_almalinux
# reboot = true
# strategy = restrict
# complexity = medium
# disruption = low



- name: Check page_alloc.shuffle argument exists
  ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*page_alloc.shuffle=' /etc/default/grub
  check_mode: False
  failed_when: False
  changed_when: False
  register: argcheck

- name: Check page_alloc.shuffle argument exists
  ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
  check_mode: False
  failed_when: False
  changed_when: False
  register: linecheck

- name: Add page_alloc.shuffle argument
  ansible.builtin.lineinfile:
    line: 'GRUB_CMDLINE_LINUX="page_alloc.shuffle=1 "'
    state: present
    dest: /etc/default/grub
    create: yes
    mode: '0644'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc != 0

- name: Replace existing page_alloc.shuffle argument
  ansible.builtin.replace:
      path: /etc/default/grub
      regexp: 'page_alloc.shuffle=[a-zA-Z0-9,]+'
      replace: 'page_alloc.shuffle=1'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and linecheck.rc == 0

- name: Add page_alloc.shuffle argument
  ansible.builtin.replace:
      path: /etc/default/grub
      regexp: '(^\s*GRUB_CMDLINE_LINUX=.*)"'
      replace: '\1 page_alloc.shuffle=1"'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc == 0


- name: Check if page_alloc.shuffle argument is already present in /etc/default/grub
  ansible.builtin.slurp:
    src: /etc/default/grub
  register: etc_default_grub

- name: Check if page_alloc.shuffle argument is already present
  ansible.builtin.command: /sbin/grubby --info=ALL
  register: grubby_info
  check_mode: False
  changed_when: False
  failed_when: False

- name: Update grub defaults and the bootloader menu
  ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="page_alloc.shuffle=1"
  when: (grubby_info.stdout is not search('page_alloc.shuffle=1')) or ((etc_default_grub['content'] | b64decode) is not search('page_alloc.shuffle=1'))

