execute commands on remote host in a Jenkinsfile

Shoaib Iqbal picture Shoaib Iqbal · Mar 20, 2019 · Viewed 14.2k times · Source

i am trying to ssh into a remote host and then execute certain commands on the remote host's shell. Following is my pipeline code.

pipeline {
    agent any
    environment {
        // comment added
         APPLICATION = 'app'
         ENVIRONMENT = 'dev'
         MAINTAINER_NAME = 'jenkins'
         MAINTAINER_EMAIL = '[email protected]'
    }
    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 [email protected] -o StrictHostKeyChecking=no'
                        sh "echo pwd"
                        sh 'sudo -i -u root'
                        sh 'cd /opt/docker/web'
                        sh 'echo pwd'
                    }
                 }
             }
         }
     }
}

But upon running this job it executes sh 'ssh -t -t [email protected] -o StrictHostKeyChecking=no' successfully but it stops there and does not execute any further commands. I want to execute the commands that are written after ssh command inside the remote host's shell. any help is appreciated.

Answer

Prikkeldraad picture Prikkeldraad · Mar 20, 2019

I would try something like this:

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