---
- name: Create user {{ user }}
  hosts: labs
  vars:
    user: user-ansible
    sshkey: /home/rocky/.ssh/id_rsa.pub
    sshpriv: /home/rocky/.ssh/id_rsa
  tasks:

    - name: Create user {{ user }}
      ansible.builtin.user:
        name: "{{ user }}"
        create_home: true
        state: present

    - name: Add user to sudoer {{ user }}
      community.general.sudoers:
        name: "{{ user }}"
        user: "{{ user }}"
        nopassword: true
        commands: ALL
        state: present

    - name: Set authorized key taken from file
      ansible.posix.authorized_key:
        user: "{{ user }}"
        key: "{{ lookup('file', '{{ sshkey }}') }}"
        state: present

    - name: Test ssh connexion
      ansible.builtin.command: ssh -i {{ sshpriv }} {{ user }}@{{ item }} sudo -l
      delegate_to: localhost
      become: false
      register: ssh_out
      changed_when: false
      ignore_errors: true
      with_items:
        - "{{ groups['labs'] }}"

    - name: Log SSH command result
      ansible.builtin.debug:
        var: item
      when: item.rc == 0
      with_items:
        - "{{ ssh_out['results'] }}"

    - name: Check if user can execute sudo
      ansible.builtin.command: sudo -l
      become: true
      become_user: "{{ user }}"
      register: sudo_out
      changed_when: false
      ignore_errors: true

    - name: Log sudo -l command
      ansible.builtin.debug:
        var: sudo_out
      when: sudo_out.rc == 0
