Call ssh-copy-id in an Ansible playbook - How to handle password prompt?

时间:2015-07-28 15:42:34

标签: ssh ansible ansible-playbook

I have two servers. I manage serverA with Ansible. serverB is not managed with Ansible. I want serverA to be able to access serverB by copying the ssh_pub_key of serverA to serverB.

This can be done manually by calling ssh-copy-id user@serverB on serverA.

I want to do this with Ansible on serverA automatically.

- name: Register ssh key at serverB
  command: ssh-copy-id -i /home/{{user}}/.ssh/id_rsa.pub -o StrictHostKeyChecking=no user@serverB

Calling ssh-copy-id requires me to enter my ssh password for user@serverB, so the key can be copied.

How can I do this via ansible? I want it to ask for the user@serverB password interactively while executing the playbook. Storing the password in ansible vault is also an option. Then I still do not know how to avoid the interactive password call of ssh-copy-id though.

I also added -o StrictHostKeyChecking=no to the call because this is another interaction that normally requires user interaction when calling ssh-copy-id.

2 个答案:

答案 0 :(得分:5)

您可以尝试使用sshpass工具。它需要修改你的命令,如下所示:

command: sshpass -p password ssh-copy-id -i /home/{{user}}/.ssh/id_rsa.pub -o StrictHostKeyChecking=no user@serverB

但如何提供密码还有其他选择 - 请参阅sshpass(1)手册页。

答案 1 :(得分:0)

如果不限制使用ssh-copy-id命令,则不妨尝试使用Ansible authorized_key模块。

然后您的代码可能如下所示:

authorized_key:
  user: <user>
  key: "{{ lookup('file', '/home/' + lookup('env', 'USER') + '/.ssh/id_rsa.pub') }}"