在 Jenkinsfile 中的远程主机上执行 shell 命令

时间:2021-01-27 23:39:13

标签: jenkins continuous-integration jenkins-plugins jenkins-groovy

为什么在连接到远程主机后,其他命令如 docker rm 和 docker run 在本地执行,而不是在远程主机上执行。如何通过远程主机使用 ssh 连接执行在第一个命令之后编写的命令?

                  if (params.Env == 'test') {
                    sshagent (credentials: ['*****-****-****-****-********']) {
                    
                        sh 'ssh -o StrictHostKeyChecking=no -l root *.*.*.* uname -a'
                        sh "docker rm mycontainer-'${params.Env}' -f"
                        sh "docker run -d -p 1234:8090 --name mycontainer-'${params.Env}' 10.0.0.1:5050/myproj:'${params.Env}'-'${currentBuild.number}'"
                        
                    }
                }

1 个答案:

答案 0 :(得分:0)

在这种情况下应该使用 Jenkins 的凭据绑定插件 - https://www.jenkins.io/doc/pipeline/steps/credentials-binding/

例如:

withCredentials([sshUserPrivateKey(credentialsId: 'ssh_pkey', keyFileVariable: 'identity', passphraseVariable: '', usernameVariable: 'jenkins')]) {
                
def remote=[:]

remote.name = '$params.Env'

remote.host = 'your_ip_address'

remote.user = 'root'

remote.identityFile=identity

remote.allowAnyHosts = true

sshCommand remote: remote, command: "docker rm container_name -f"

sshCommand remote: remote, command: "docker run -d -p 443:443 --restart always --name 
container_name