Quick-Tip: Use host ssh-agent in Docker

Introduction

As I described in another post, I usually do all my Yocto builds inside a docker container. This worked well, but when I was in a project where some of the recipes needed to clone git repositories using ssh-keys I realized I needed a nice way to share my host systems keys automatically. Luckily, this is just what ssh-agent do, so all that had to be done was to make sure that the system inside the docker container could access the hosts ssh-agent socket.

The Solution

The environment variable SSH_AUTH_SOCK is used to determine the path to the socket used for communicating with ssh-agent. This means that on the host system we can use this to find the path to the socket, so that it can be bind-mounted into the container. Then we tell docker to set SSH_AUTH_SOCK inside the container to the path where it was mounted.

In the previous post I set up my alias used to start the containers to:

alias pokydocker='docker run --rm -it -v ${PWD}:${PWD} pokyextended --workdir ${PWD}'

If we now pass an extra -v option for the bind-mount, and a -e for setting up SSH_AUTH_SOCK, all should be good.

alias pokydocker='docker run --rm -it -v ${PWD}:${PWD} -v ${SSH_AUTH_SOCK}:/ssh.socket -e SSH_AUTH_SOCK=/ssh.socket --workdir ${PWD}'

The Aftermath

And with this, I lived happily ever after, right? Not really. All was working well until one day when I was working remotely and wanted to start a Yocto build over ssh. When I connect to my host system over ssh there’s nothing that starts an ssh-agent automatically, so SSH_AUTH_SOCK was empty and then fetching the sources would fail inside the container.

So I figured I should make sure ssh-agent is start on ssh logins, and then all would be good again. Said and done, and it worked fine until that time I started my build in a screen session and realized that the ssh-agent was killed when I logged out. Actually it took me time to realize what was going on, and one or more bad words might have been uttered. In the end I realized that the easiest way was to just use the socket from my local session (I basically always have a local session running), which is available under /run/user/1000/keyring/ssh, by running export SSH_AUTH_SOCK=/run/user/1000/keyring/ssh after login in via ssh, but before starting the docker container.

Leave a Reply

Your email address will not be published. Required fields are marked *