---
# file: roles/ssh-keygen-and-store/tasks/main.yml

- name: "make sure the .ssh directory exists"
  file:
    path: "{{ getent_passwd[item[0].item][4] }}/.ssh"
    state: directory
    owner: "{{ item[0].item }}"
    group: "{{ item[0].item }}"
  tags: ssh-keygen

- name: "generate key"
  openssh_keypair:
    path: "{{ getent_passwd[item[0].item][4] }}/.ssh/id_ed25519"
    type: ed25519
    comment: "{{ item[0].item }}@{{ ansible_hostname }}"
    owner: "{{ item[0].item }}"
  tags: ssh-keygen

- name: "register the key in variable"
  command: "cat {{ getent_passwd[item[0].item][4] }}/.ssh/id_ed25519"
  ignore_errors: True
  changed_when: False
  register: generated_key
  tags: ssh-keygen

- name: "register the public key in variable"
  command: "cat {{ getent_passwd[item[0].item][4] }}/.ssh/id_ed25519.pub"
  ignore_errors: True
  changed_when: False
  register: generated_key_pub
  tags: ssh-keygen

- name: "put the newly generated key in ansible vault"
  delegate_to: localhost
  become: no
  command: 'vault kv patch talas-kv/{{ host_vars_location }}/{{ ansible_hostname }} ssh_key_ed25519_{{ item[0].item }}="{{ generated_key.stdout }}" ssh_key_ed25519_{{ item[0].item }}_pub="{{ generated_key_pub.stdout }}"'
  tags: ssh-keygen
