Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Jenkins pipeline and java.nio.file.* methods

I am trying to use methods from java.nio.file.* to perform some basic file operations in a Jenkins pipeline. Regardless of the node block in which the code exists, the code executes on the master node. In the pipeline, I have verified that the various node blocks are correct--they uniquely identify specific nodes. However, pathExists (and other code that moves, copies, or deletes files) always executes on the master node. Any ideas what's happening or how to fix it?

import java.nio.file.*

String slavePath = 'C:\\Something\\only\\on\\slave\\node'
String masterPath = 'D:\\Something\\only\\on\\master\\node'

def pathExists (String pathName)
{
    def myPath = new File(pathName)
    return (myPath.exists()) 
}

stage('One') 
{
    node ('slave')
    {
        bat returnStatus: true, script: 'set'
        println (pathExists(slavePath))     // Should be true but is false.
        println (pathExists(masterPath))    // Should be false but is true.
    }
    node ('master')
    {
        bat returnStatus: true, script: 'set'
        println (pathExists(slavePath))     // false
        println (pathExists(masterPath))    // true
    }
}
like image 623
gaccardo Avatar asked Sep 28 '16 17:09

gaccardo


1 Answers

This is a specification of pipeline script. It's written in the tutorial.

  • readFile step loads a text file from the workspace and returns its content (do not try to use java.io.File methods — these will refer to files on the master where Jenkins is running, not in the current workspace).

  • There is also a writeFile step to save content to a text file in the workspace

  • fileExists step to check whether a file exists without loading it.

You can use those Jenkins steps in a node instead of java.io.File or java.nio.file.Files as below.

String slavePath = 'C:\\Something\\only\\on\\slave\\node'
String masterPath = 'D:\\Something\\only\\on\\master\\node'

stage('One') 
{
    node ('slave')
    {
        bat returnStatus: true, script: 'set'
        println fileExists(slavePath)     // Should be true
        println fileExists(masterPath)    // Should be false
    }
    node ('master')
    {
        bat returnStatus: true, script: 'set'
        println fileExists(slavePath)     // false
        println fileExists(masterPath)    // true
    }
}
like image 163
arasio Avatar answered Nov 12 '22 15:11

arasio