Building Docker Images Without Exposing Private SSH Keys

I've been fighting with getting a docker image built that has to pull from a private github repo, and after talking to CircleCI support I only had one more step to figure out, so I thought I'd share the important bits here.

The main piece they provided was to enable a newer version of Docker, and set up experimental on the docker daemon. This includes some interesting info: the ability to ssh remote-docker where you have root access via sudo. Also interesting is that they have newer versions of docker available, but stick to older versions as default to preserve compatibility with existing builds.

  - setup_remote_docker:
      version: 19.03.13
  - run: |
      ssh remote-docker \<<EOF
        sudo bash -c 'echo "{\"experimental\": true}" > /etc/docker/daemon.json'
        sudo systemctl restart docker

Include this content in your Dockerfile

# syntax = docker/dockerfile:1.0-experimental
RUN --mount=type=ssh,id=github git clone ...

Then run:

DOCKER_BUILDKIT=1 docker build --ssh=github="${ssh_private_key_location}"

This results in a docker image that does not include the private ssh key. I verified this by running docker save and grepping the tar file.