2018.04.24

Deploying code from the Docker container using the ssh-agent

For some years ago I have completely moved my development environment to Docker containers.

It's easy and fun to set up the soft you need for a specific project by just adding several lines of code to your 'docker-compose.yml` file. And so easy the removal of the software you don't need anymore is too.

I've used to use software like Vagrant before. But is was even a bit more complicated than the Docker is. And it got some disk IO drawbacks when used together with VirtualBox shared folders or with directories mounted with netfs/samba.

So the workflow based on Docker became a nice speed improvement for development workflow in general.

Deploying code from GitHub

The only one problem remained. How should I launch the deploy script (bundle exec cap production deploy in my case) from the container? And how it will work with Docker? I don't like to enter my password every time I want to deploy.

My first attempt was to add an rsa key directly to my image:

  • Rather manually by calling docker cp ~/.ssh/id_rsa 888d87685a68:/root where the 888d87685a68 is an id of my container;

  • Or by adding the ADD ./id_rsa /root/.ssh/id_rsa instruction directly to my Dockerfile;

The both methods above will work but they both have their drawbacks. When choosing the first one you'll need to execute this command every time the container is rebuilt. When choosing the second way the risk to mistakenly deploy your private key with the container occures.

Actually you don't need to copy your private key to your container (and you better not do it).

All you need is the ssh-agent installed and launched on both: your host and your docker container then all you need to do is to mount the ssh-aget's socket file:

If you are using docker-compose:


environment:
  - "SSH_AUTH_SOCK=/tmp/ssh-agent"
volumes:
  - $SSH_AUTH_SOCK:/tmp/ssh-agent

When running Docker without the Docker Compose script the commands will look like:


docker run -v $SSH_AUTH_SOCK:/tmp/ssh-agent 8be57bbc9561 sleep 1000000 # 8be57bbc9561 is an id of the image
docker exec -it -e SSH_AUTH_SOCK=/tmp/ssh-agent 5b6f4a8f8661 /bin/ash # 5b6f4a8f8661 is an id of the container

P.S.

Don't forget to run eval "$(ssh-agent -s)" && ssh-add on both: your host and your container. You can check if the key was added by calling ssh-add -l command.

If you like this post you'll probably like the other one SSH client configuration tricks.