# platform = multi_platform_all
# reboot = false
# strategy = restrict
# complexity = low
# disruption = low






- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Check if watch rule for /var/log/journal/ already exists in /etc/audit/rules.d/
  ansible.builtin.find:
    paths: "/etc/audit/rules.d"

    contains: '^\s*-w\s+/var/log/journal/\s+-p\s+wa(\s|$)+'

    patterns: "*.rules"
  register: find_existing_watch_rules_d

- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Search /etc/audit/rules.d for other rules with specified key systemd_journal
  ansible.builtin.find:
    paths: "/etc/audit/rules.d"
    contains: '^.*(?:-F key=|-k\s+)systemd_journal$'
    patterns: "*.rules"
  register: find_watch_key
  when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Use /etc/audit/rules.d/systemd_journal.rules as the recipient for the rule
  ansible.builtin.set_fact:
    all_files:
      - /etc/audit/rules.d/systemd_journal.rules
  when: find_watch_key.matched is defined and find_watch_key.matched == 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Use matched file as the recipient for the rule
  ansible.builtin.set_fact:
    all_files:
      - "{{ find_watch_key.files | map(attribute='path') | list | first }}"
  when: find_watch_key.matched is defined and find_watch_key.matched > 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Add watch rule for /var/log/journal/ in /etc/audit/rules.d/
  ansible.builtin.lineinfile:
    path: "{{ all_files[0] }}"

    line: "-w /var/log/journal/ -p wa -k systemd_journal"

    create: yes
    mode: '0600'
  when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Check if watch rule for /var/log/journal/ already exists in /etc/audit/audit.rules
  ansible.builtin.find:
    paths: "/etc/audit/"

    contains: '^\s*-w\s+/var/log/journal/\s+-p\s+wa(\s|$)+'

    patterns: "audit.rules"
  register: find_existing_watch_audit_rules

- name: Ensure auditd Collects records for events that affect "/var/log/journal" - Add watch rule for /var/log/journal/ in /etc/audit/audit.rules
  ansible.builtin.lineinfile:

    line: "-w /var/log/journal/ -p wa -k systemd_journal"

    state: present
    dest: /etc/audit/audit.rules
    create: yes
    mode: '0600'
  when: find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched == 0
