Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In docker, how to scope with the requirement of configuring known_hosts, authorized_keys and ssh connectivity in general, when container have to talk with external systems?

For example, I'm running jenkins container and try to checkout the project from github in job, but connection fails with the error host key verification failed

This could be solved by login into container, connect to github manually and trust the host key when prompted. However this isn't proper solution, as everything needs to be 100% automated (I'm building CI pipeline with ansible and docker). Another (clunky) solution would be to provision the running container with ansible, but this would make things messy and hard to maintain. Jenkins container doesn't even has ssh daemon, and I'm not sure how to ssh into container from other host. Third option would be to use my own Dockerfile extending jenkins image, where ssh is configured, but that would be hardcoding and locking the container to this specific environment.

So what is the correct way with docker to manage (and automate) connectivity with external systems?

like image 499
Tuomas Toivonen Avatar asked Nov 07 '16 16:11

Tuomas Toivonen


3 Answers

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.

like image 103
Konstantin Suvorov Avatar answered Nov 02 '22 19:11

Konstantin Suvorov


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

ARG PRIVATE_SSH_KEY

# Authorize SSH Host
RUN 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 keys
RUN 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).

like image 8
basickarl Avatar answered Nov 02 '22 18:11

basickarl


One solution is to mount host's ssh keys into docker with following options:

docker run -v /home/<host user>/.ssh:/home/<docker user>/.ssh <image>

This works perfectly for git.

like image 4
Mohammad Azim Avatar answered Nov 02 '22 18:11

Mohammad Azim