Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute commands on remote host in a Jenkinsfile

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.

like image 475
Shoaib Iqbal Avatar asked Mar 20 '19 12:03

Shoaib Iqbal


3 Answers

I resolve this issue

script 
{
    sh """ssh -tt login@host << EOF 
    your command
    exit
    EOF"""
}
like image 104
Alexey Avatar answered Nov 02 '22 20:11

Alexey


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"'
}
like image 44
Prikkeldraad Avatar answered Nov 02 '22 18:11

Prikkeldraad


    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
                    """
                }
        }
    }
like image 22
vijay sanwal Avatar answered Nov 02 '22 18:11

vijay sanwal