---
# Вывод участников привилегированных групп (root, wheel, sudo) на всех управляемых хостах.
# Отмечает пользователей, которые НЕ определены в group_vars/all/users.yml.
# Запуск:  ansible-playbook -i inventory/prod playbooks/audit_root_group.yml
- name: Audit privileged group members
  hosts: all
  gather_facts: false
  become: true

  vars:
    known_usernames: >-
      {{
        users_admin_groups.values()
        | sum(start=[])
        | map(attribute='username')
        | list
      }}

  tasks:
    - name: Get members of privileged groups
      ansible.builtin.command: getent group {{ item }}
      register: group_entries
      changed_when: false
      failed_when: group_entries.rc not in [0, 2]
      loop:
        - root
        - wheel
        - sudo

    - name: Parse group members
      ansible.builtin.set_fact:
        privileged_groups: >-
          {{
            privileged_groups | default([]) + [{
              'group': item.item,
              'members': (item.stdout.split(':')[3].split(',') | select) | list
                         if item.rc == 0 and item.stdout != '' else []
            }]
          }}
      loop: "{{ group_entries.results }}"
      loop_control:
        label: "{{ item.item }}"

    - name: Show privileged group members
      ansible.builtin.debug:
        msg: >-
          {{ inventory_hostname }} — {{ item.group }}:
          {% if item.members | length == 0 %}(none)
          {% else %}
          {{ item.members | join(', ') }}
          {% set unknown = item.members | difference(known_usernames) %}
          {% if unknown | length > 0 %}
          | UNKNOWN (not in users.yml): {{ unknown | join(', ') }}
          {% endif %}
          {% endif %}
      loop: "{{ privileged_groups }}"
      loop_control:
        label: "{{ item.group }}"
      when: item.members | length > 0 or item.group == 'root'
