Docker, how to deal with ssh keys, known_hosts and authorized_keys Docker, how to deal with ssh keys, known_hosts and authorized_keys jenkins jenkins

Docker, how to deal with ssh keys, known_hosts and authorized_keys


To trust github.com host you can issue this command when you start or build your container:

 ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

This will add github public key to your known hosts file.


If everything is done in the Dockerfile it's easy.In my Dockerfile:

ARG PRIVATE_SSH_KEY# Authorize SSH HostRUN mkdir -p /root/.ssh && \    chmod 0700 /root/.ssh && \    ssh-keyscan example.com > /root/.ssh/known_hosts && \    # Add the keys and set permissions    echo "$PRIVATE_SSH_KEY" > /root/.ssh/id_rsa && \    chmod 600 /root/.ssh/id_rsa...do stuff with private key# Remove SSH keysRUN rm -rf /root/.ssh/

You need to obviously need to pass the private key as an argument to the building(docker-compose build or docker build).


This is how I do it, not sure if you will like this solution though. I have a private git repository containing authorized_keys with a collection of public keys. Then, I use ansible to clone this repository and replace authorized_keys:

- git: repo=my_repo dest=my_local_folder force=yes accept_hostkey=yes- shell: "cp my_local_folder/authorized_keys ~/.ssh/"

Using accept_hostkey is what actually allows me to automate the process (I trust the source, of course).