0

I need to ssh to a server from a simple jenkin pipeline and make a deploy which is simply moving to a directory and do a git fetch and some other comands (nmp install among others). Thing is that when jenkin job ssh to the remote server it connects ok but then It gets stucked, I have to stop it. I just now modify the script to simply do a "ssh to server " and a "pwd command" to go to the easiest but it connects to it and it get stuck untill I abort. What Am I missing? here is the simpe pipeline script and the output on an screenshot

pipeline {
agent any 
stages {
    stage('Connect to server') {
        steps {
            sh "ssh -t -t jenkins@10.x.x.xx"
            sh "pwd"

        }
    }

    stage('branch status') {
        steps {
            sh "git status"
        }
    }
}

}

enter image description here

Chanafot
  • 566
  • 1
  • 13
  • 28

1 Answers1

1

Jenkins executes each "sh" step as a separate shell script. Content is written to a temporary file on Jenkins node and only then executed. Each command is executed in separate session and is not aware of previous one. So neither ssh session or changes in environment variable will persist between the two.

More importantly though, you are forcing pseudo-terminal allocation with -t flag. This is pretty much opposite to what you want to achieve, i.e. run shell commands non-interactively. Simply

sh "ssh jenkins@10.x.x.xx pwd"

is enough for your example to work. Placing the commands on separate lines would not work with regular shell script, regardless of Jenkins. However you still need to have private key available on node, otherwise the job will hang, waiting for you to provide password interactively. Normally, you will want to use SSH Agent Plugin to provide private key at runtime.

script {
    sshagent(["your-ssh-credentals"]) {
        sh "..."
    }
}

For execution on longer commands see What is the cleanest way to ssh and run multiple commands in Bash?

Majus Misiak
  • 487
  • 4
  • 11
  • if I don´t add -t -t I get: "sudo: no tty present and no askpass program specified" – Chanafot Apr 24 '18 at 19:53
  • That is expected, since running sudo command will prompt you for a pasword, interactively. You can add "jenkins ALL=(ALL) NOPASSWD: ALL" on target machine with "sudo visudo" but I really discourage that. You are unlikely needing sudo for "git fetch" or "npm install" commands. – Majus Misiak Apr 25 '18 at 05:03