jenkins-pipeline

Jenkins execute sshCommand sequentialy


I am trying to execute several command with Pipeline with SSHCommand but I'am not able to do what I want :

pipeline {
   agent any

   stages {
      stage('Generate File') {
         steps {
           script {
             def remote = [:]
             remote.name = 'test'
             remote.host = 'xxxxxxx'
             remote.user = 'xxxxxxx'
             remote.port = xxxxxxxx
             remote.password = 'xxxxxxxx'
             remote.allowAnyHosts = true
             sshCommand remote: remote, command: "cd /var/my/directory"
             sshCommand remote: remote, command: "touch pipeline"
           }
         } 
      }
   }
}

But the file "pipeline" is created in "/home/myUser" not in /var/my/directory"

How can i do this ? I need to use "&&" ?

This works :

sshCommand remote: remote, command: "cd /var/my/directory && touch MyFile"

But I don't like "single line"

Thanks,


Solution

  • What basically happens, is that each call of sshCommand starts its own shell (very much like if you were to open two different terminals on your computer). After the command the shell is closed again.

    So your code does:

    1. Open a remote shell (in the home dir)
    2. Go to directory /var/my/directory"
    3. Close the shell
    4. Start a new one (in the home dir)
    5. touch pipeline

    One way around this would be a single command touch /var/my/directory/pipeline or like you said &&. If you want to put it in multiple lines you can use \.

    sshCommand remote: remote, command: "cd /var/my/directory \
                                          && touch pipeline"