问题描述
在 Jenkins Pipeline 中,需要在远程主机上执行命令。当然可以直接执行 ssh(1)命令,但是该方法可移植性较差,并非最佳实践;
该笔记将记录:在 Jenkins Pipeline 中,如何使用 SSH 命令的方法,及相关问题的解决办法;
解决方案
安装 SSH Pipeline Steps 插件: 1)插件主页:https://plugins.jenkins.io/ssh-steps/#plugin-content-sshput 2)使用文档:https://www.jenkins.io/doc/pipeline/steps/ssh-steps/ 3)项目主页:https://github.com/jenkinsci/ssh-steps-plugin#sshput
远程执行命令
然后,在 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 p[……]
READ MORE