← All Articles

Pulling Git into a Docker image without leaving SSH keys behind

Khash SajadiKhash Sajadi
Sep 9th 15Updated Nov 28th 17

pulling-git-into-a-docker-image-without-leaving-ssh-keys-behind

Adding your code to a docker image is as easy as using an ADD command into your Dockerfile. This will essentially copy your code onto the image. However many languages and frameworks will require other steps to be taken from here onwards. For example a bundle install in a Rails application might want to pull the source of a gem from a private repository, or running go get on a Go project might require the private SSH keys to a git repository.

The simplest way to address this issue is to add your private SSH key to the docker image. However this is not ideal as you will end up with your private SSH key on a docker image, open to inspection by anyone who has access to it.

I can think of two ways to work around this issue:

  • Pull the SSH private key from a secret vault and put it into tmpfs and add that file to the ssh-agent.
  • Copy the SSH private key to the image, add it to the ssh-agent and then remove the key and squash the layers created to remove the file and any traces of it from the image.

The first method requires having a hosted secret vault that can serve you with the private key through a curl command. I will write about the details of this method in near future.

The second method is easier to implement. Here is how it can work:

  • Add the private key to the Dockerfile
  • Add it to the ssh-agent
  • Run the commands that require SSH authentication
  • Remove the private key
  • Squash the layers

Here is an example:

Dockerfile

ADD ~/.ssh/mykey /tmp/
RUN ssh-agent /tmp
# RUN bundle install or similar command
RUN rm /tmp/mykey

Let’s build the image now:

$ docker build -t original .

Now we need to squash the image with something like Docker Squash:

$ docker save original | sudo docker-squash -t squashed | docker load

original is the image ID of the created image

You can now push the squashed image up to a Docker repository and remove the original image.

$ docker rmi original

This method works fine with most scenarios, but adds to the build time (squash step). I will write about the first method of using a secret vault and curl next.


Related blog post: Using SSH Private key securely in Docker build -->



Try Cloud 66 for Free, No credit card required