I needed that to add jenkins pubkey to my host's authorized_keys when starting a docker container with jenkins. Looked for solutions, but could not find ready at internet. May seem obvious, but not for me at least :)
3 Answers
PUBKEY=$(cat ~/.ssh/id_rsa.pub); grep -q "$PUBKEY" ~/.ssh/authorized_keys || echo "$PUBKEY" >> ~/.ssh/authorized_keys
This one-liner checks whether pubkey is already present in authorized_keys file, and appends it to the end of file if it is not present.
~/.ssh/id_rsa.pub here is path to pubkey being added
~/.ssh/authorized_keys here is a path to target authorized_keys file (~ symbol is the home directory i.e /home/accountname/)
For remote host, one can use ssh-copy-id
You may want to skip the whole idea of messing around with ~/.ssh/authorized_keys and just use SSH CA feature as described, for example, here: https://www.digitalocean.com/community/tutorials/how-to-create-an-ssh-ca-to-validate-hosts-and-clients-with-ubuntu (scroll down to "How To Configure User Keys").
The beauty of this is that you configure your container once (by adding TrustedUserCAKeys /etc/ssh/users_ca.pub where users_ca.pub contains the public part of the CA key generated on your local machine) and from that point on if you want to grant access to the container to any key you just sign the public part of that key with your CA private key and specify which accounts are allowed for the key you are signing. Works like magic :)
-
Thank you for info. I did not know about TrustedUserCAKeys feature. It does not suit better in my case (jenkins in container is used for backups, and the goal is to avoid manual configuration of SSH on every host I'm going to run the container on. So I just need to add a single allowed key), but it sounds really useful for other applicationsDmitriusan– Dmitriusan2015-09-07 06:13:22 +00:00Commented Sep 7, 2015 at 6:13
Assuming that the public key is in ~/.ssh/id_rsa.pub, then you may add it unconditionally to the ~/.ssh/authorized_keys file and use sort -u on that file to remove duplicates:
# Make sure that the file exists and has the correct permissions
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# Add new key, removing duplicates.
sort -u -o ~/.ssh/authorized_keys ~/.ssh/authorized_keys ~/.ssh/id_rsa.pub