Jenkins Pipeline SSH 鉴权


在公司搭建测试环境时,使用流水线远程部署阶段一直使用的是用户名和密码登录的方式。但是会有服务器只能使用密钥登录的情况。流水线密钥远程在网上资料比较少,这次实践成功将结果记录下来。

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

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值