Re-use already running ssh-agent if any

prepareSshAgentKey() will not start ssh-agent if there is already
running any ssh-agent process, as the result there will be no
"config" file (~/.ssh/ssh-agent.sh) and runSshAgentCommand fails

Instead we need to re-use already running ssh-agent and re-construct
  * SSH_AUTH_SOCK
  * SSH_AGENT_PID

E.g:
  [env-01-configure-system] Running shell script
   + head -n 1
   + grep /tmp/ssh-.*/agent.*
   + find /tmp/ -type s -name agent.*
   + export SSH_AUTH_SOCK=/tmp/ssh-NQmNvs9SM9wu/agent.5363
   + echo /tmp/ssh-NQmNvs9SM9wu/agent.5363
   + cut -d. -f2
   + export SSH_AGENT_PID=5363
   + ssh-add /home/jenkins/.ssh/id_rsa_deployments-key
   Identity added: /home/jenkins/.ssh/id_rsa_deployments-key (/home/jenkins/.ssh/id_rsa_deployments-key)

Change-Id: I1e7126513fa623c83b5fdd3448a4654e24f09e33
diff --git a/src/com/mirantis/mk/ssl.groovy b/src/com/mirantis/mk/ssl.groovy
index 24ccd52..fcdea5a 100644
--- a/src/com/mirantis/mk/ssl.groovy
+++ b/src/com/mirantis/mk/ssl.groovy
@@ -24,7 +24,20 @@
  * @param cmd   Command to execute
  */
 def runSshAgentCommand(cmd) {
-    sh(". ~/.ssh/ssh-agent.sh && ${cmd}")
+    // if file exists, then we started ssh-agent
+    if (fileExists("$HOME/.ssh/ssh-agent.sh")) {
+        sh(". ~/.ssh/ssh-agent.sh && ${cmd}")
+    } else {
+    // we didn't start ssh-agent in prepareSshAgentKey() because some ssh-agent
+    // is running. Let's re-use already running agent and re-construct
+    //   * SSH_AUTH_SOCK
+    //   * SSH_AGENT_PID
+        sh """
+        export SSH_AUTH_SOCK=`find /tmp/ -type s -name agent.\\* 2> /dev/null |  grep '/tmp/ssh-.*/agent.*' | head -n 1`
+        export SSH_AGENT_PID=`echo \${SSH_AUTH_SOCK} | cut -d. -f2`
+        ${cmd}
+        """
+    }
 }
 
 /**
@@ -35,8 +48,9 @@
 def prepareSshAgentKey(credentialsId) {
     def common = new com.mirantis.mk.common()
     c = common.getSshCredentials(credentialsId)
-    sh("test -d ~/.ssh || mkdir -m 700 ~/.ssh")
-    sh('pgrep -l -u $USER -f | grep -e ssh-agent\$ >/dev/null || ssh-agent|grep -v "Agent pid" > ~/.ssh/ssh-agent.sh')
+    // create ~/.ssh and delete file ssh-agent.sh which can be stale
+    sh('mkdir -p -m 700 ~/.ssh && rm -f ~/.ssh/ssh-agent.sh')
+    sh('pgrep -l -u $USER -f ssh-agent\$ >/dev/null || ssh-agent|grep -v "Agent pid" > ~/.ssh/ssh-agent.sh')
     sh("set +x; echo '${c.getPrivateKey()}' > ~/.ssh/id_rsa_${credentialsId} && chmod 600 ~/.ssh/id_rsa_${credentialsId}; set -x")
     runSshAgentCommand("ssh-add ~/.ssh/id_rsa_${credentialsId}")
 }