在公司搭建测试环境时,使用流水线远程部署阶段一直使用的是用户名和密码登录的方式。但是会有服务器只能使用密钥登录的情况。流水线密钥远程在网上资料比较少,这次实践成功将结果记录下来。
pipeline 进行远程操作需要安装插件 SSH pipeline Step
ssh pipeline 更多的操作请查阅官方文档
下面分别介绍密码和密钥两种方式:
usernamePassword
stage('SSH') {
steps {
script {
def remote = [:]
remote.name = 'xxx'
remote.host = 'xx.xx.xxx.xxx'
remote.allowAnyHosts = true
withCredentials([usernamePassword(credentialsId: 'myCredential', passwordVariable: 'password', usernameVariable: 'username')]) {
remote.user = "${username}"
remote.password = "${password}"
}
sshCommand remote: remote, command: "pwd"
}
}
}
credentialsId 是jenkins的凭据,该凭据新增时选择用户名密码类型。
host是服务器IP地址。name由自己定义。
sshUserPrivateKey
stage('SSH') {
steps {
script {
def remote = [:]
remote.name = 'xxx'
remote.host = 'xx.xx.xxx.xxx'
remote.allowAnyHosts = true
withCredentials([sshUserPrivateKey(credentialsId: 'myCredential', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'userName')]) {
remote.user = userName
remote.identityFile = identity
sshCommand remote: remote, command:'pwd'
writeFile file: 'test.sh', text: 'ls'
sshPut remote: remote, from: 'test.sh', into: '.'
}
}
}
}
credentialsId 是jenkins的凭据,该凭据新增时选择用户名密钥类型。
需要注意的是,远程操作命令的作用域在withCredentials中,如果和用户名密码方式一样写在withCredentials外则会报错。
Jenkins Pipeline 学习可参考我之前写的博客
https://blog.csdn.net/qq_36450484/article/details/100556861