如果要將 public key 複製到機器上,對單台來說很容易

~$ ssh-copy-id -i ~/.ssh/id_rsa.pub **remote host**

可是如果需要對多台機器做 ssh-copy,除了寫 Shell Script,還可以使用 Ansible 的 authorized_key modules 完成。

hosts:

[cluster]
**remote host** ansible_user=**username** ansible_ssh_pass="**password**"

ssh.yaml:

- hosts: cluster
  user: ming
  tasks:
      - name: ssh-copy
        authorized_key:
            user: ming
            key: "{{ lookup('file', '/home/ming/.ssh/id_rsa.pub') }}"

接著在 Terminal 輸入:

~$ ansible-playbook ssh.yaml
PLAY [cluster] *************************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [IP]

TASK [ssh-copy] ************************************************************************************************************************************************************
changed: [IP]

PLAY RECAP *****************************************************************************************************************************************************************
IP              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0