Skip to content

Instantly share code, notes, and snippets.

@cowlicks
Last active September 11, 2023 19:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowlicks/1c0d6973b894d46b1a0ea6cd99bc7852 to your computer and use it in GitHub Desktop.
Save cowlicks/1c0d6973b894d46b1a0ea6cd99bc7852 to your computer and use it in GitHub Desktop.
Safely share your SSH access while building a Dockerfile using socat to forward ssh-agent's SSH_AUTH_SOCK
#!/usr/bin/env bash
# ensure the processes get killed when we're done
trap 'kill $(jobs -p)' EXIT
# create a connection from port 56789 to the unix socket SSH_AUTH_SOCK (which is used by ssh-agent)
socat TCP-LISTEN:56789,reuseaddr,fork UNIX-CLIENT:${SSH_AUTH_SOCK} &
# Run docker
# Pass it all the command line args ($@)
# set the network to "host" so docker can talk to localhost
docker $@ --network='host'
FROM python:3-stretch
COPY . /app
WORKDIR /app
RUN mkdir -p /tmp
# install socat and ssh to talk to the host ssh-agent
RUN apt-get update && apt-get install git socat openssh-client \
# create variable called SSH_AUTH_SOCK, ssh will use this automatically
&& export SSH_AUTH_SOCK=/tmp/auth.sock \
# make SSH_AUTH_SOCK useful by connecting it to hosts ssh-agent over localhost:56789
&& /bin/sh -c "socat UNIX-LISTEN:${SSH_AUTH_SOCK},unlink-early,mode=777,fork TCP:localhost:56789 &" \
# stuff I needed my ssh keys for
&& mkdir -p ~/.ssh \
&& ssh-keyscan gitlab.com > ~/.ssh/known_hosts \
&& pip install -r requirements.txt

My original comment is here. It explains how to use this script to safely share your SSH access with docker during a build. This lets you easily install things from private repos during docker build. In this example I use pip to install a package from a private repo on gitlab.

The wrapper script, and example Dockerfile are included. Here is how to use them:

$ docker_with_host_ssh.sh build -f ../docker/Dockerfile 
...
from -r requirements.txt (line 23)
  Cloning ssh://git@gitlab.com/...
...
Successfully built 7aae96739921 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment