Using FilePath to access a workspace on a slave in a Jenkins pipeline

I need to check for a specific .exe file in my workspace as part of my pipeline assembly job. I tried using the below Groovy script from my Jenkins file to do the same. But I think the File class, by default, tries to find the workspace directory on the jenkins wizard and fails.

@com.cloudbees.groovy.cps.NonCPS def checkJacoco(isJacocoEnabled) { new File(pwd()).eachFileRecurse(FILES) { it -> if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') isJacocoEnabled = true } } 

How to access a file system on a slave using Groovy from inside a Jenkins file?

I also tried the code below. But I get the error No such property: build for class: groovy.lang.Binding . Instead, I tried using the manager object. But get the same error.

 @com.cloudbees.groovy.cps.NonCPS def checkJacoco(isJacocoEnabled) { channel = build.workspace.channel rootDirRemote = new FilePath(channel, pwd()) println "rootDirRemote::$rootDirRemote" rootDirRemote.eachFileRecurse(FILES) { it -> if (it.name == 'jacoco.exec' || it.name == 'Jacoco.exec') { println "Jacoco Exists:: ${it.path}" isJacocoEnabled = true } } 
+5
source share
1 answer

Had the same problem, found this solution:

 import hudson.FilePath; import jenkins.model.Jenkins; node("aSlave") { writeFile file: 'a.txt', text: 'Hello World!'; listFiles(createFilePath(pwd())); } def createFilePath(path) { if (env['NODE_NAME'] == null) { error "envvar NODE_NAME is not set, probably not inside an node {} or running an older version of Jenkins!"; } else if (env['NODE_NAME'].equals("master")) { return new FilePath(path); } else { return new FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path); } } @NonCPS def listFiles(rootPath) { print "Files in ${rootPath}:"; for (subPath in rootPath.list()) { echo " ${subPath.getName()}"; } } 

The important thing is that createFilePath() not annotated with @NonCPS , since it needs access to the env variable. Using @NonCPS removes access to Pipeline Good, but, on the other hand, does not require all local variables to be serializable. You can then search for the file inside the listFiles() method.

+10
source

Source: https://habr.com/ru/post/1261594/


All Articles