I ran into this topic and just wanted to report back how I got it working, because there’s some misinformation.
The general principle for passwordless access from HA to another server:
- Create ssh keys without a password on the HA machine, using ssh-keygen (don’t type a password when it asks for it)
- Do ssh-copy-id on the HA machine, to update the authorized_keys file on the remote server
- Connect once, and answer yes to update the known_hosts file on the HA machine
From then on, you have passwordless access to the remote machine.
There is no need to store the private or public key from the remote machine on the HA machine.
(by which I mean, physically moving the files using scp)
However, things are a little more complex when running HA in docker.
In order to store the settings persistently, you do need some options in the ssh command.
I have HA running via docker-compose and have this volume: /home/pi/homeassistant:/config
.
By default, a docker shell runs as root, meaning ssh certificates and known_hosts file are stored under /root/.ssh
, which is not persistent after container restart, so you need to change that.
- Start a shell in the HA container:
docker exec -it <container name> /bin/bash
- In
/config
, make a folder ssh (you can call this what you want):
mkdir /config/ssh
- Now execute
ssh-keygen
, but when it asks for the file location, make sure you type/config/ssh/id_rsa
. Also, don’t use a password, otherwise you will never get passwordless access. - Now push the public key to the remote machine using
ssh-copy-id
. Because we didn’t use the default location for the key, we need to tell it where it is (-i flag):
ssh-copy-id -i /config/ssh/id_rsa.pub <user>@<remote-ip>
During this, it will ask you for the remote ssh password once (this is the last time). - Now the final, but important step: you need to connect once and answer the question yes to update the local known_hosts file. However, because you are root, it will store it again under
/root/.ssh/known_hosts
, so we need to give it a different location again (with -o flag):
ssh -i /config/ssh/id_rsa -o UserKnownHostsFile=/config/ssh/known_hosts <user>@<remote-ip>
You might get an error message saying: WARNING: UNPROTECTED PRIVATE KEY FILE!
This is because the keys were created by root.
This is quickly solved by:
sudo chmod 600 /config/ssh/id_rsa
sudo chmod 600 /config/ssh/id_rsa.pub
Now do step 5 again.
If all went well, now you have passwordless access.
You can now do stuff like:
ssh -i /config/ssh/id_rsa -o UserKnownHostsFile=/config/ssh/known_hosts <user>@<remote-pi> 'sudo poweroff'
(on a remote Raspberry Pi)