---
- name: Create user {{ user }}
  hosts: labs
  vars:
    user: webadmin
    sshkey: /home/rocky/.ssh/id_rsa.pub
  tasks:
    - name: Execute block
      block:
        - name: Create user {{ user }}
          ansible.builtin.user:
            name: "{{ user }}"
            create_home: true
            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: su - rocky -c 'ssh -o StrictHostKeyChecking=no {{ user }}@{{ item }} "exit 0"'
          delegate_to: localhost
          become: false
          register: ssh_out
          changed_when: false
          with_items:
            - "{{ groups['labs'] }}"

      rescue:
        - name: Delete user {{ user }}
          ansible.builtin.user:
            name: "{{ user }}"
            state: absent
      always:
        - name: Show user info
          ansible.builtin.command: id {{ user }}
          changed_when: false
          register: info

        - name: Write log to file
          ansible.builtin.lineinfile:
            line: "{{ info }}"
            path: /tmp/ansible.log
          delegate_to: localhost
