2019
Dec
06
It is easy to link an existing ssh-agent into a docker container, just to add the environment SSH_AUTH_SOCK
. But it will be broken if you recreate an ssh-agent from the host, for some big companies, ssh-agent forward only could live for a couple of hours force you to create a one.
Example
- -e SSH_AUTH_SOCK=$SSH_AUTH_SOCK
Solution: I use symbolic link to solve this problem, add a script to your bashrc to find a existing ssh-agent and create a link from ~/docker_tmp/ssh-agent
to /tmp/ssh-oYYYqv4X/agent.12831
, Any time when you have a new ssh-agent, trigger this shell to relink them.
Example
start docker script
- function linkSshAgent {
- # link ssh-agent for docker container
- if [ -d ~/docker_tmp ];then
- if [ -f ~/docker_tmp/ssh-agent ];then
- rm -f ~/docker_tmp/ssh-agent
- fi
- mkdir -p ~/docker_tmp/ssh-agent/
- # change the dirname of the ssh-agent tmpdir, I don't want to mount host /tmp to container /tmp
- # -v /tmp:/host_tmp
- socket_name=$(echo $socket_name | sed 's/\/tmp\//\/host_tmp\//')
- ln -sf $socket_name ~/docker_tmp/ssh-agent/ssh-agent
- fi
- }
Example
- docker run -d -t --name $containerName \
- -h "$containerName" \
- -v ~/docker_tmp/ssh-agent/:/docker_tmp/ssh-agent/:ro \
- -v /tmp:/host_tmp:ro \
- -e SSH_AUTH_SOCK=/docker_tmp/ssh-agent/ssh-agent \
- $imageName /bin/bash
- ~/docker_tmp/ssh-agent/:/docker_tmp/ssh-agent/:ro fixed the ssh-agent file name , I create a ssh-agent on host
- /tmp:/host_tmp:ro, the only way to change the ssh agent temporary dir is change the env
TEMPDIR
, I don't want to change this env.
- SSH_AUTH_SOCK=/docker_tmp/ssh-agent/ssh-agent : specific the ssh-agent file path.
Example
- ls -la /docker_tmp/ssh-agent/ssh-agent
- lrwxrwxrwx 1 64675 users 36 Apr 21 02:16 /docker_tmp/ssh-agent/ssh-agent -> /host_tmp/ssh-oYYenCqa4X/agent.19236