「Jenkins Pipeline」- SSH

  CREATED BY JENKINSBOT

内容简介

本文介绍在Jenkins Pipeline中,如何使用SSH命令,及相关的工具。

问题描述

在Jenkins Pipeline中,需要在远程主机上执行命令。当然可以直接执行ssh(1)命令,但是这不够Jenkins Pipeline啊,而且可移植性较差,并不是最佳实践。

解决办法

安装插件:「SSH Pipeline Steps

然后,在Jenkins Pipeline中使用如下代码:

def remote = [:]
remote.name = 'test'
remote.host = 'test.domain.com'
remote.user = 'root'
remote.password = 'password'
remote.allowAnyHosts = true

sshCommand remote: remote, command: "ls -lrt"

但安全性较低:因为密码不应该直接进行编码,而是应该是创建Credentials后,再使用代码获取。如下示例:

// 注意,我们这里跳过了创建Credentials的方法

// 在Jenkinsfile中
withCredentials([usernamePassword(credentialsId: "Your-Credentials-Id", usernameVariable: "username", passwordVariable: "password")]) {

	def remote = [:]
	remote.name = 'test'
	remote.host = 'test.domain.com'
	remote.user = username
	remote.password = password
	remote.allowAnyHosts = true

	sshCommand remote: remote, command: "ls -lrt"
}

// 在共享库中有点不同
//「共享库」与「Jenkinsfile」二者是有差别的。主要在于对变量的理解上。 由withCredentials生成
// 的变量是位于环境中的,所以要到env中获取。
class Foo {

	Script pipeline // 在Jenkinsfile中,以new Foo(this)的形式实例化

	Foo(Script pipeline) {
		this.pipeline = pipeline
	}

	public void bar() {
		this.pipeline.withCredentials([usernamePassword(credentialsId: "Your-Credentials-Id", usernameVariable: "username", passwordVariable: "password")]) {

			def remote = [:]
			remote.name = 'test'
			remote.host = 'test.domain.com'
			remote.user = this.pipeline.env.username // 变量是注入到环境变量中的
			remote.password = this.pipeline.env.password // 变量是注入到环境变量中的
			remote.allowAnyHosts = true

			sshCommand remote: remote, command: "ls -lrt"
		}
	}
}

当然支持SSH私钥访问:

def remote = [:]
remote.name = "node-1"
remote.host = "10.000.000.153"
remote.allowAnyHosts = true

node {
    withCredentials([sshUserPrivateKey(credentialsId: 'sshUser', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'userName')]) {
        remote.user = userName
        remote.identityFile = identity

        stage("SSH Steps Rocks!") {
            writeFile file: 'abc.sh', text: 'ls'
            sshCommand remote: remote, command: 'for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done'
        }
    }
}

(注意,上一个示例中「Jenkinsfile」与「共享库」的差别,这里不再展开)

相关链接

手册:Pipeline Steps Reference/SSH Pipeline Steps
示例:GitHub/jenkinsci/ssh-steps-plugin

另外,还需要了解以下「Credentials Binding」插件,及对应的「Pipeline Steps Reference/Credentials Binding Plugin」手册,该插件负责获取Jenkins中配置的各种Credentials信息,以提高Pipeline的安全性及可移植性。

参考文献

Pipeline Steps Reference/SSH Pipeline Steps
SSH Steps for Jenkins Pipeline