Configuring SSH Agent Plugin for Jenkins on Windows
I've been using Git for Windows for a long time now, and I struggled with fundamentally the same issue. When working with github or other remote ssh repos, I wanted to be able to open multiple windows but have them all share the same ssh agent.
Below is the full content of what I call my assure_ssh_agent
shell function for Git Bash. Source its definition in every independent session that you run. I have the following two lines in my ~/.profile
.
. ~/ssh-agent.shassure_ssh_agent
After the function has been defined you can ssh-add your keyfiles or, if you define a list of them in .ssh/keylist
, you can just run addkeys
, which will load all of them into the agent for 10 hours by default, which should be enough for a normal working day and long lunchbreak.
How it works: The script maintains shared state in the file .ssh/pid_store
.If assure_ssh_agent()
cannot find a valid pid it will start a new agent, and write its pid and socket there, for any subsequent session.
Contents of ssh-agent.sh
:
# echo $SSH_AUTH_SOCK $SSH_AGENT_PIDis_running() { (kill -0 ${1:?PID}) 2> /dev/null}agent_pid_store() { ( pid_store=$HOME/.ssh/agent_pid touch -a $pid_store case $1 in ( read ) read pid sock < $pid_store && echo $pid $sock [ -n "$sock" ] ;; ( write) echo \ ${SSH_AGENT_PID:?} \ ${SSH_AUTH_SOCK:?} > $pid_store ;; ( clear ) rm -f ${pid_store:?} esac )}find_active_ssh_agent() { ( set -- $(agent_pid_store read) pid=$1 sock=$2 case $1 in ("") return 1 ;; ($SSH_AGENT_PID) is_running $SSH_AGENT_PID && echo $SSH_AGENT_PID $2 ;; (*) is_running $pid && echo $pid $sock && return return 1 ;; esac )}ssh_agent_is_running() { (find_active_ssh_agent | read _was_there_something_to_read_)}assure_ssh_agent() { unset GIT_SSH unset SVN_SSH set -- $( find_active_ssh_agent ) && pid=$1 sock=$2 : "pid='$pid' sock='$sock'" : "length: pid:${#pid} sock:${#sock}" case $pid$sock in ( "" ) printf "* " >& 2 eval $( ssh-agent ) > /dev/null agent_pid_store write echo "ssh agent ${SSH_AGENT_PID}" >& 2 return ;; ( * ) export SSH_AGENT_PID=$pid SSH_AUTH_SOCK=$sock echo "ssh agent ${SSH_AGENT_PID}" >& 2 set +x return ;; esac}addkeys(){ (set -e #-x unset GIT_SSH unset SVN_SSH Keyfile_Timeout=36000 cd ~/.ssh exec < keylist || exit 1 $(echo >& 2 "Add names of keyfiles to $HOME/.ssh/keylist") while read keyfile do ssh-add -t ${Keyfile_Timeout} ~/.ssh/$keyfile done )}