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

a7qyws3x  于 2022-11-02  发布在  Jenkins
关注(0)|答案(4)|浏览(222)

我正在尝试ssh到远程主机,然后在远程主机的shell上执行某些命令。

pipeline {
    agent any
    environment {
        // comment added
         APPLICATION = 'app'
         ENVIRONMENT = 'dev'
         MAINTAINER_NAME = 'jenkins'
         MAINTAINER_EMAIL = 'jenkins@email.com'
    }
    stages {
         stage('clone repository') {
             steps {
                 // cloning repo
                 checkout scm
             }
         }
         stage('Build Image') {
             steps {
                 script {
                     sshagent(credentials : ['jenkins-pem']) {
                        sh "echo pwd"
                        sh 'ssh -t -t ubuntu@xx.xxx.xx.xx -o StrictHostKeyChecking=no'
                        sh "echo pwd"
                        sh 'sudo -i -u root'
                        sh 'cd /opt/docker/web'
                        sh 'echo pwd'
                    }
                 }
             }
         }
     }
}

但在运行此作业时,它成功执行sh 'ssh -t -t ubuntu@xx.xxx.xx.xx -o StrictHostKeyChecking=no',但它停止在那里,并不执行任何进一步的命令。我想执行在远程主机的shell内的ssh命令之后编写的命令。任何帮助都是感激的。

col17t5w

col17t5w1#

我会尝试这样的方法:

sshagent(credentials : ['jenkins-pem']) {
  sh "echo pwd"
  sh 'ssh -t -t ubuntu@xx.xxx.xx.xx -o StrictHostKeyChecking=no "echo pwd && sudo -i -u root && cd /opt/docker/web && echo pwd"'
}
v440hwme

v440hwme2#

我解决此问题

script 
{
    sh """ssh -tt login@host << EOF 
    your command
    exit
    EOF"""
}
zujrkrfu

zujrkrfu3#

stage("DEPLOY CONTAINER"){
        steps {
            script {
                    sh """
                    #!/bin/bash
                    sudo ssh -i /path/path/keyname.pem username@serverip << EOF
                    sudo bash /opt/filename.sh
                    exit 0
                    << EOF
                    """
                }
        }
    }
d6kp6zgx

d6kp6zgx4#

有一个更好的方法来运行命令远程使用SSH。我知道这是迟来的答案,但我刚刚探索了这件事,所以想分享,这将有助于其他人解决这个问题很容易。
我刚刚发现this link对如何使用SSH在远程运行多个命令很有帮助。我们也可以像上面的博客中提到的那样有条件地运行多个命令。通过浏览它,我发现了语法:
;(semicolon)
现在,如何在Jenkins管道中使用SSH在远程hots内部运行命令?
解决方案如下:

pipeline {
  agent any
  environment {
    /*
     define your command in variable
     */
    remoteCommands =
      """java --version;
    java --version;
    java --version """
  }
  stages {
    stage('Login to remote host') {
      steps {
        sshagent(['ubnt-creds']) {
          /*
              Provide variable as argument in ssh command
          */
          sh 'ssh -tt username@hostanem $remoteCommands'
        }
      }
    }
  }
}

首先(可选),您可以定义一个变量来保存由;(semicolon)分隔的所有命令,然后将其作为command中的参数传递。
另一种方法是,也可以将命令直接传递给ssh命令,
sh "ssh -tt username@hostanem 'command1;command2;commandN'"
我已经在我的代码中使用了它,它工作得很好!see the output here
快乐学习:)

相关问题