Surender Panuganti
Surender Panuganti

Reputation: 343

How to copy a file from Jenkins Agent node to a remote server using Jenkinsfile

I have a Jenkinsfile which implements a pipeline and in one of the stages and under a node, if I say unstash 'myfile', where this 'myfile' will be available on the node? My requirement is I need to access this file and copy to a known remote server (this remote server is not part of Jenkins pool) as part of the Jenkinsfile script.

Upvotes: 3

Views: 18702

Answers (2)

MaratC
MaratC

Reputation: 6859

I say unstash 'myfile', where this 'myfile' will be available on the node?

You don't do unstash 'myfile', you do unstash 'my_stash', where my_stash is the name you used when you saved your stash previously. The stash can contain one file, or it can contain a whole directory tree. Its contents is defined at the moment you stash it (relative to ${WORKSPACE} on the node running stash) and it's unstashed in exactly the same way, relative to ${WORKSPACE} on the node running unstash.

The workspace is located according to your agent configuration (at my place, it's in /Users/jenkins/workspace/<a folder Jenkins creates>), but for all the practical purposes -- as your steps on the node are running in that folder too -- you can refer to it as ., e.g.

stage ('stash') {
   node { label  'one' }
   steps {
       script {
           sh "echo 1 > myfile.txt" // runs in $WORKSPACE, creates $WORKSPACE/myfile.txt
           stash name: "my_stash", includes: "myfile.txt" // relative to $WORKSPACE
       }
   }
}

stage ('unstash') {
   node { label  'two' }
   steps {
       script {
           unstash name: "my_stash"  // runs in $WORKSPACE, creates $WORKSPACE/myfile.txt
           sh "cat ./myfile.txt"
       }
   }
}

Upvotes: 2

Sers
Sers

Reputation: 12255

You can use SSH Pipeline Steps to copy file to a remote server. Here is example how to send file from job workspace to remote host:

remote = [:]

remote.name = "name"
remote.host = "remote_ip"
remote.allowAnyHosts = true
remote.failOnError = true
withCredentials([usernamePassword(credentialsId: 'credentials_name', passwordVariable: 'password', usernameVariable: 'username')]) {
    remote.user = username
    remote.password = password
}

sshPut remote: remote, from: 'myfile', into: 'folder_on_remote_host'

Upvotes: 5

Related Questions