- hosts: demo
  gather_facts: no
  tasks:
    - name: Get users
      ansible.builtin.shell:
        cmd: >
          getent passwd | awk -F: '$7 !~ /(false|nologin|true|sync)$/' | grep -v '^$' | awk -F":" '{ print $1 }'
      register: users

    - name: Gather posix account last login
      ansible.builtin.shell: |
        for user in {{ users.stdout_lines | join(" ") }}; do
          last -wi --time-format iso -n 1 ${user}  | awk '{ print $1,$3,$4, $NF }' | head -1 | awk 'NF'
        done
      register: last_login

    - name: Get user password change date and expiry
      ansible.builtin.shell: |
        for user in {{ users.stdout_lines | join(" ") }}; do
          k=$(getent shadow $user | awk -F: '{ print $3, $5 }')
          echo "$user:$k"
        done
      register: passwd_date

    - name: Get user groups
      ansible.builtin.shell: |
        for user in {{ users.stdout_lines | join(" ") }}; do
          echo "$(groups $user)" | sed 's@ : @:@g'
        done
      register: user_groups

    - name: Get sudoers
      ansible.builtin.shell: |
        for user in {{ users.stdout_lines | join(" ") }}; do
          echo "$user: $(grep "^$user " /etc/sudoers | tr '\n' ';' || echo '')"
        done
      register: user_sudo

    - name: Get authorized keys
      ansible.builtin.shell: |
        for user in {{ users.stdout_lines | join(" ") }}; do
          home=$(getent passwd $user | cut -d: -f6)
          echo -n "$user:"
          if [ -f "${home}/.ssh/authorized_keys" ]; then
            cat ${home}/.ssh/authorized_keys | tr '\n' ';'
          fi
          echo
        done
      register: user_authorized

    - set_fact:
        info:
          users: "{{ users.stdout_lines }}"
          last_login: "{{ last_login.stdout_lines }}"
          user_groups: "{{ user_groups.stdout_lines }}"
          user_sudo: "{{ user_sudo.stdout_lines }}"
          user_authorized: "{{ user_authorized.stdout_lines }}"
          passwd_date: "{{ passwd_date.stdout_lines }}"

    - debug:
        var: info
