blob: fcdea5aef1d35dde91d8ef17099afbce5bfe44b5 [file] [log] [blame]
Sergey Kolekonovba203982016-12-21 18:32:17 +04001package 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 */
14def 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 */
26def runSshAgentCommand(cmd) {
Sergey Kulanovf36af072017-01-20 13:35:57 +020027 // 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 Kolekonovba203982016-12-21 18:32:17 +040041}
42
43/**
44 * Setup ssh agent and add private key
45 *
46 * @param credentialsId Jenkins credentials name to lookup private key
47 */
48def prepareSshAgentKey(credentialsId) {
iberezovskiy67af6c22016-12-26 18:17:21 +040049 def common = new com.mirantis.mk.common()
50 c = common.getSshCredentials(credentialsId)
Sergey Kulanovf36af072017-01-20 13:35:57 +020051 // 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 Kulanov6307d342016-12-27 14:29:31 +020054 sh("set +x; echo '${c.getPrivateKey()}' > ~/.ssh/id_rsa_${credentialsId} && chmod 600 ~/.ssh/id_rsa_${credentialsId}; set -x")
Sergey Kolekonovba203982016-12-21 18:32:17 +040055 runSshAgentCommand("ssh-add ~/.ssh/id_rsa_${credentialsId}")
56}
57
58return this;