# platform = multi_platform_rhel
# reboot = true
# strategy = configure
# complexity = medium
# disruption = low

- name: "Ensure BLS boot entries options contain page_alloc.shuffle=1"
  block:
    - name: "Check how many boot entries exist "
      ansible.builtin.find:
        paths: "/boot/loader/entries/"
        patterns: "*.conf"
      register: n_entries

    - name: "Check how many boot entries set page_alloc.shuffle=1"
      ansible.builtin.find:
        paths: "/boot/loader/entries/"
        contains: "^options .*page_alloc.shuffle=1.*$"
        patterns: "*.conf"
      register: n_entries_options

    - name: "Update boot entries options"
      ansible.builtin.command: grubby --update-kernel=ALL --args="page_alloc.shuffle=1"
      when: n_entries is defined and n_entries_options is defined and n_entries.matched != n_entries_options.matched

    - name: "Check if /etc/kernel/cmdline exists"
      ansible.builtin.stat:
        path: /etc/kernel/cmdline
      register: cmdline_stat

    - name: "Check if /etc/kernel/cmdline contains page_alloc.shuffle=1"
      ansible.builtin.find:
        paths: "/etc/kernel/"
        patterns: "cmdline"
        contains: "^.*page_alloc.shuffle=1.*$"
      register: cmdline_find

    - name: "Add /etc/kernel/cmdline contains page_alloc.shuffle=1"
      ansible.builtin.lineinfile:
        create: yes
        path: "/etc/kernel/cmdline"
        line: 'page_alloc.shuffle=1'
      when: cmdline_stat is defined and not cmdline_stat.stat.exists

    - name: "Append /etc/kernel/cmdline contains page_alloc.shuffle=1"
      ansible.builtin.lineinfile:
        path: "/etc/kernel/cmdline"
        backrefs: yes
        regexp: "^(.*)$"
        line: '\1 page_alloc.shuffle=1'
      when: cmdline_stat is defined and cmdline_stat.stat.exists and cmdline_find is defined and cmdline_find.matched == 0
