Forward Host Ssh-Agent to Docker Builds on MacOS

Situation and Goal

A dependency of your crate that you want to containerize is a git repository referenced in your Cargo.toml. You are a responsible developer and use passphrases for your SSH keys, running SSH key-agent. You don’t want to copy private keys onto a Docker-image. With these constraints cargo cannot fetch the sources on build when run inside Docker during the Dockerfile build script, well not without some access to the ssh-agent.

Solution

Lots of outdated discussions lead to using the “magic path” SSH_AUTH_SOCK=/run/host-services/ssh-auth.sock on macOS. This is not needed at all, here are the needed steps, compatible with Linux too:

  1. Enable ForwardAgent in your ssh config for the target host, to do that add this to your ~/.ssh/config file on your computer
Host github.com
  ForwardAgent yes
  1. Use the Docker-build feature --ssh to auto-forward your ssh-agent using a “mount”. For your docker-compose.yaml this looks like this
# ...
services:
  your-service:
    build:
      ssh: ['default'] # mount default ssh-agent

Command line call: docker build --ssh default .. Instead of “default” one could reference a custom ssh-agent socket.

  1. In your Dockerfile, when you do something ssh related, use RUN --mount=type=ssh, so in the given case
RUN --mount=type=ssh cargo build --release

If you are trying to something else using ssh and it fails, you can verify that the ssh-agent forwarding works, by listing the loaded keys:

RUN --mount=type=ssh ssh-add -l
  1. Optionally: Assuming that you use StrictHostKeyChecking in your SSH config, also add the target-host’s public-key to your .cargo/config.toml
[net.ssh]
known-hosts = [
  "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"
]
# If you have a complicated setup, make cargo use ssh executable instead of its built-in ssh library
# by changing this to `true`
# make sure to have openssh-client available in your docker image
[net]
git-fetch-with-cli = false