- name: Configure SSH
  hosts: athelas
  tasks:

  - name: Generate RSA4096 SSH key
    community.crypto.openssh_keypair:
      path: "~/ssh_key"
      size: 4096

  - name: Get SSH Private Key
    ansible.builtin.fetch:
      dest: "~/ansible/keys/"
      src: "~/ssh_key"
      flat: true

  - name: Get SSH Public Key
    ansible.builtin.fetch:
      dest: "~/ansible/keys/"
      src: "~/ssh_key.pub"
      flat: true

  - name: Copy new SSH configuration
    ansible.builtin.template:
      src: "~/ansible/templates/sshd_config.j2"
      dest: "/etc/ssh/sshd_config"

  - name: Create new user
    ansible.builtin.user:
      name: "motysten"
      groups: "sudo"
      shell: /bin/bash
      append: true
      password: "{{ lookup('password', '/tmp/userpass length=12 encrypt=sha512_crypt') }}"
    become: true

  - name: Display password
    ansible.builtin.debug:
      msg: "Password : {{ lookup('file', '/tmp/userpass') }}"

  - name: Add SSH public key to remote host
    ansible.builtin.authorized_key:
      user: "motysten"
      key: "{{ lookup('file', '~/ansible/keys/ssh_key.pub') }}"
    become: true

  - name: Restart SSH Services
    ansible.builtin.service:
      name: "{{ item }}"
      state: restarted
    become: true
    with_items:
      - ssh
      - sshd

- hosts: 127.0.0.1
  connection: local
  tasks:

  - name: Delete pass file
    ansible.builtin.file:
      path: /tmp/userpass
      state: absent
