Skip to content

Instantly share code, notes, and snippets.

@leedm777
Created August 12, 2015 15:29
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save leedm777/923706741c8296869e7d to your computer and use it in GitHub Desktop.
Save leedm777/923706741c8296869e7d to your computer and use it in GitHub Desktop.
Run docker, forwarding your SSH agent into the container
#!/bin/sh
#
# Forwards SSH agent into a Docker container running in the active
# docker-machine
#
PROGNAME=$(basename $0)
NAME=$(docker-machine active)
if test -z "${NAME}"; then
echo "${PROGNAME}: Must active a docker machine with `eval $(docker-machine env [machine-name])`" >&2
exit 1
fi
# Setup SSH forwarding into docker host
# From https://gist.github.com/rcoup/53e8dee9f5ea27a51855
SSH_SOCK=docker.${NAME}.$$.ssh.socket
SSH_PORT=$(docker-machine inspect -f '{{.Driver.SSHPort}}' ${NAME})
# Most ssh options copied from docker-machine ssh
# Others:
# -A - Enables forwarding of the authentication agent connection
# -M - Places the ssh client into ``master'' mode for connection sharing
# -S - Specifies the location of a control socket for connection sharing
# -f - Requests ssh to go to background just before command execution
# -n - Redirects stdin from /dev/null
# tail -f /dev/null - command that never ends
ssh -i $HOME/.docker/machine/machines/${NAME}/id_rsa \
-o PasswordAuthentication=no \
-o IdentitiesOnly=yes \
-o StrictHostKeyChecking=no \
-o UserKnownHostsFile=/dev/null \
-o LogLevel=quiet \
-o ConnectionAttempts=3 \
-o ConnectTimeout=10 \
-p ${SSH_PORT} \
docker@localhost \
-A -M -S $SSH_SOCK -f -n \
tail -f /dev/null
DM_AGENT_SOCK=$(ssh -S $SSH_SOCK docker@localhost echo \$SSH_AUTH_SOCK)
# Try our best to kill the socket on exit
trap "ssh -S $SSH_SOCK -O exit docker@localhost" EXIT
docker run \
-v $DM_AGENT_SOCK:/ssh-agent \
-e "SSH_AUTH_SOCK=/ssh-agent" \
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment