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:
- Enable
ForwardAgentin your ssh config for the target host, to do that add this to your~/.ssh/configfile on your computer
Host github.com
ForwardAgent yes
- Use the Docker-build feature
--sshto auto-forward your ssh-agent using a “mount”. For yourdocker-compose.yamlthis 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.
- In your
Dockerfile, when you do something ssh related, useRUN --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
- Optionally: Assuming that you use
StrictHostKeyCheckingin 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