Call ssh-copy-id in an Ansible playbook - How to handle password prompt?
Solution 1
If using the ssh-copy-id
command is not a restriction, you might as well try out the Ansible authorized_key
module.
Then your code could look something like this:
authorized_key:
user: <user>
key: "{{ lookup('file', '/home/' + lookup('env', 'USER') + '/.ssh/id_rsa.pub') }}"
Solution 2
You can try sshpass
tool. It would require modification of your command like this:
command: sshpass -p password ssh-copy-id -i /home/{{user}}/.ssh/id_rsa.pub -o StrictHostKeyChecking=no user@serverB
but there are other options how to provide the password -- see the sshpass(1)
manual page.
funkenstrahlen
Updated on July 28, 2022Comments
-
funkenstrahlen almost 2 years
I have two servers. I manage
serverA
with Ansible.serverB
is not managed with Ansible. I wantserverA
to be able to accessserverB
by copying thessh_pub_key
ofserverA
toserverB
.This can be done manually by calling
ssh-copy-id user@serverB
onserverA
.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. -
funkenstrahlen almost 9 yearsThat's a great approach. How can I interactively ask for the password before, so I can pass the variable to sshpass?
-
Jakuje over 7 yearsbefore what? You are running in cron.
-
Rao over 3 yearsI would just add, that Ansible link points to docs for old version. Current version is here.
-
akshaypmurgod almost 2 yearsthis does not work on cento7 & above.
-
Jakuje almost 2 years@akshaypmurgod why? What does it do?
-
akshaypmurgod almost 2 yearsIt doesn`t error out. At the same time, ssh keys are not copied to the destination server. Any suggestions are welcome.
-
Jakuje almost 2 years@akshaypmurgod you can run the
ansible
orssh
in verbose mode to see what is going on there.