---
- name: Set Debian family AppArmor grub cmdline
  become: true
  ansible.builtin.lineinfile:
    line: 'GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX apparmor=1 security=apparmor"'
    dest: /etc/default/grub.d/99-hardening-apparmor.cfg
    state: present
    create: true
    mode: "0640"
    owner: root
    group: root
  when: ansible_os_family == "Debian"
  notify:
    - Update GRUB
  tags:
    - apparmor
    - CIS-UBUNTU2004-1.6.1.2

- name: Configure pam_apparmor
  become: true
  ansible.builtin.lineinfile:
    line: "session optional pam_apparmor.so order=user,group,default"
    dest: /etc/pam.d/apparmor
    state: present
    create: true
    mode: "0640"
    owner: root
    group: root
  when: ansible_os_family == "Debian"
  notify:
    - Update GRUB
  tags:
    - apparmor

- name: Get AppArmor status
  become: true
  environment:
    PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  ansible.builtin.command: aa-status --complaining
  register: get_apparmor_complaining
  changed_when: get_apparmor_complaining.stdout != "0"
  when: ansible_os_family == "Debian"
  tags:
    - apparmor

- name: Enforce AppArmor profiles
  become: true
  ansible.builtin.command:
    cmd: find /etc/apparmor.d/ -maxdepth 1 -type f -exec aa-enforce {} \;
  register: enforce_apparmor_profiles
  changed_when: enforce_apparmor_profiles.rc != 0
  failed_when: enforce_apparmor_profiles.rc != 0
  when: ansible_os_family == "Debian" and (get_apparmor_complaining.stdout != "0")
  tags:
    - apparmor
    - CIS-UBUNTU2004-1.6.1.3
    - CIS-UBUNTU2004-1.6.1.4

- name: Enable apparmor
  become: true
  ansible.builtin.systemd:
    name: apparmor
    enabled: true
    state: started
  when: ansible_os_family == "Debian"
  tags:
    - apparmor
