jenkins pipeline 通过withCredentials连接项目服务器进行自动部署

场景

在项目服务器上已经存在发布更新脚本(包含从git拉取代码,更新代码,发布),只需执行就可以,但是必须在服务器的指定目录下执行, 所以需要在Jenkins pipeline,能实现远程登录到项目服务器,并且去执行对应的脚本来更新

withCredentials实现方式

pipeline {
    agent any
    stages {
        stage('update enviroment') {
            steps{
                echo "update ****"
                dir('exist_dir') {  // 到指定目录执行一下内容
                   sh 'pwd'
                   checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: '5806fc55-141d-4f26-9204-955b18c66ac0', url: 'https://****.git']]])
                    .....
                 }
            script{
                def remote = [:]    //定义远程连接的remote
                remote.name = "name***"
                remote.host = '*.*.*.*'
                remote.port = 22
                remote.allowAnyHosts = true
                withCredentials([sshUserPrivateKey(credentialsId: 'c71e7770-a7e0-4ef4-aa91-052a12250350', keyFileVariable: 'identity', usernameVariable: 'username')]) {   // 通过Pipeline Syntax 自动生成
                    remote.user = username
                    remote.identityFile = identity
                    echo "update ** "
                    sh "scp -r -P ${remote.port}  ${env.WORKSPACE}/exist_dir/* ${remote.user}@${remote.host}:/*/*/*"   //在Jenkins服务器上执行scp命令,把前面exist_dir中需要的文件拷贝到指定目录
                    sshCommand remote: remote, command: '/bin/bash **.sh' //链接远程服务器,执行脚本
                    sshCommand remote: remote, command: 'export PATH=$PATH:/**/** && /bin/bash **/deploy.sh' //通过export添加执行脚本需要的环境变量
                }
              }
            }
       }
       .....
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值