# platform = multi_platform_all
# reboot = false
# strategy = configure
# complexity = low
# disruption = high




   



- name: "Add nosuid Option to /boot/efi: Check filesystem type of /boot/efi"
  ansible.builtin.command: findmnt --kernel --raw --evaluate --output=FSTYPE '/boot/efi'
  register: fs_type_check
  failed_when: fs_type_check.rc > 1
  changed_when: False
  check_mode: False

- name: "Add nosuid Option to /boot/efi: Set fact for excluded filesystem"
  set_fact:
    is_excluded_fstype: "{{ fs_type_check.rc == 0 and 'vfat' in fs_type_check.stdout_lines }}"


- name: "Add nosuid Option to /boot/efi: Check information associated to mountpoint"
  ansible.builtin.command: findmnt --fstab '/boot/efi'
  register: device_name
  failed_when: device_name.rc > 1
  changed_when: False
  check_mode: False

  when: not is_excluded_fstype | default(false)


- name: "Add nosuid Option to /boot/efi: Create mount_info dictionary variable"
  set_fact:
    mount_info: "{{ mount_info|default({})|combine({item.0: item.1}) }}"
  with_together:
    - "{{ device_name.stdout_lines[0].split() | list | lower }}"
    - "{{ device_name.stdout_lines[1].split() | list }}"
  when:
    - device_name.stdout is defined and device_name.stdout_lines is defined
    - (device_name.stdout | length > 0)

    - not is_excluded_fstype | default(false)


- name: "Add nosuid Option to /boot/efi: If /boot/efi not mounted, craft mount_info manually"
  set_fact:
    mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
  with_together:
    - ["target", "source", "fstype", "options"]
    - ["/boot/efi", "", "", "defaults"]
  when:
    - ("--fstab" | length == 0)
    - device_name.stdout is defined and device_name.stdout_lines is defined
    - (device_name.stdout | length == 0)

    - not is_excluded_fstype | default(false)


- name: "Add nosuid Option to /boot/efi: Make sure nosuid option is part of the to /boot/efi options"
  set_fact:

    mount_info: "{{ mount_info | combine( {'options':''~(mount_info.options | default(''))~(',' if (mount_info.options | default('')) else '')~'nosuid' }) }}"

  when:
    - mount_info is defined and "nosuid" not in (mount_info.options | default(''))

    - not is_excluded_fstype | default(false)


- name: "Add nosuid Option to /boot/efi: Ensure /boot/efi is mounted with nosuid option"
  ansible.posix.mount:
    path: "/boot/efi"
    src: "{{ mount_info.source | default('') }}"
    opts: "{{ mount_info.options | default('') }}"
    state: "mounted"
    fstype: "{{ mount_info.fstype | default('') }}"
  register: mount_result
  failed_when:
    - mount_result is failed
    - "'target is busy' not in (mount_result.msg | default(''))"
    - "'already mounted' not in (mount_result.msg | default(''))"
  when:
    - mount_info is defined
    - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab" | length == 0)

    - not is_excluded_fstype | default(false)
