Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 1 | package com.mirantis.mk |
| 2 | |
| 3 | /** |
| 4 | * |
| 5 | * SSL functions |
| 6 | * |
| 7 | */ |
| 8 | |
| 9 | /** |
| 10 | * Ensure entry in SSH known hosts |
| 11 | * |
| 12 | * @param url url of remote host |
| 13 | */ |
| 14 | def ensureKnownHosts(url) { |
| 15 | uri = new URI(url) |
| 16 | port = uri.port ?: 22 |
| 17 | |
| 18 | sh "test -f ~/.ssh/known_hosts && grep ${uri.host} ~/.ssh/known_hosts || ssh-keyscan -p ${port} ${uri.host} >> ~/.ssh/known_hosts" |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * Execute command with ssh-agent |
| 23 | * |
| 24 | * @param cmd Command to execute |
| 25 | */ |
| 26 | def runSshAgentCommand(cmd) { |
Sergey Kulanov | f36af07 | 2017-01-20 13:35:57 +0200 | [diff] [blame^] | 27 | // if file exists, then we started ssh-agent |
| 28 | if (fileExists("$HOME/.ssh/ssh-agent.sh")) { |
| 29 | sh(". ~/.ssh/ssh-agent.sh && ${cmd}") |
| 30 | } else { |
| 31 | // we didn't start ssh-agent in prepareSshAgentKey() because some ssh-agent |
| 32 | // is running. Let's re-use already running agent and re-construct |
| 33 | // * SSH_AUTH_SOCK |
| 34 | // * SSH_AGENT_PID |
| 35 | sh """ |
| 36 | export SSH_AUTH_SOCK=`find /tmp/ -type s -name agent.\\* 2> /dev/null | grep '/tmp/ssh-.*/agent.*' | head -n 1` |
| 37 | export SSH_AGENT_PID=`echo \${SSH_AUTH_SOCK} | cut -d. -f2` |
| 38 | ${cmd} |
| 39 | """ |
| 40 | } |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Setup ssh agent and add private key |
| 45 | * |
| 46 | * @param credentialsId Jenkins credentials name to lookup private key |
| 47 | */ |
| 48 | def prepareSshAgentKey(credentialsId) { |
iberezovskiy | 67af6c2 | 2016-12-26 18:17:21 +0400 | [diff] [blame] | 49 | def common = new com.mirantis.mk.common() |
| 50 | c = common.getSshCredentials(credentialsId) |
Sergey Kulanov | f36af07 | 2017-01-20 13:35:57 +0200 | [diff] [blame^] | 51 | // create ~/.ssh and delete file ssh-agent.sh which can be stale |
| 52 | sh('mkdir -p -m 700 ~/.ssh && rm -f ~/.ssh/ssh-agent.sh') |
| 53 | sh('pgrep -l -u $USER -f ssh-agent\$ >/dev/null || ssh-agent|grep -v "Agent pid" > ~/.ssh/ssh-agent.sh') |
Sergey Kulanov | 6307d34 | 2016-12-27 14:29:31 +0200 | [diff] [blame] | 54 | sh("set +x; echo '${c.getPrivateKey()}' > ~/.ssh/id_rsa_${credentialsId} && chmod 600 ~/.ssh/id_rsa_${credentialsId}; set -x") |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 55 | runSshAgentCommand("ssh-add ~/.ssh/id_rsa_${credentialsId}") |
| 56 | } |
| 57 | |
| 58 | return this; |