# --- 
# sshkey.yml
#
# ssh-keyscan and copy your SSH key to hosts
#
# Parameters:
# targets: group in the inventory to use
# threads: number of simultaneous executions
# pubkey: file to hand off
# sshport (optional): override 22/tcp/ssh for Ansible control
#
# Expects ANSIBLE_VAULT_FILE to be set in the environment to path the vault
#
- hosts: "{{ targets | default('managed') }}"
  order: sorted
  serial: "{{ threads | default('8') }}"
  gather_facts: true
  ignore_unreachable: true
  vars: 
      ansible_ssh_password: "{{ passwords[inventory_hostname] }}"
      ansible_ssh_port: "{{ sshport | default('22') }}" 
      keyfile: "{{ pubkey | default(lookup('env','HOME') + '/.ssh/id_ed25519.pub') }}"
  vars_files:
     - "{{ lookup('env', 'ANSIBLE_VAULT_FILE') }}"

  tasks:
      # Scanning SSH keys has been replaced with ../bin/generate-ssh-keyscan
     
      - name: Get key
        delegate_to: localhost
        command: "cat {{ keyfile }}"
        register: key

      - authorized_key:
            user: "{{ ansible_user_id }}"
            key: "{{ key.stdout }}"
            state: present
            exclusive: true
        name: "Pass authorized key"
