Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file from Jenkins workspace with System groovy script

Tags:

jenkins

groovy

I have a question very similar to this: Reading file from Workspace in Jenkins with Groovy script

However I need to read the file from a System Groovy script so the solution of using Text-finder or the Groovy PostBuild plugin will not work.

How can I get the workspace path from a system groovy script? I have tried the following:

System.getenv('WORKSPACE')
System.getProperty("WORKSPACE")
build.buildVariableResolver.resolve("WORKSPACE")

Thanks!

like image 246
JamesE Avatar asked May 13 '14 16:05

JamesE


1 Answers

If you have a file called "a.txt" in your workspace, along with a script called "sysgvy.groovy" that you want to execute as a system groovy script. Suppose your "sysgvy.groovy" script needs to read the file "a.txt".

The issue of this topic is that if your script read "a.txt" directly without providing any path, "sysgvy.groovy" executes and will throw an error saying cannot find "a.txt".

I have tested and found that the following method works good.

def build = Thread.currentThread().executable

Then use

build.workspace.toString()+"\\a.txt"

as the full location string to replace "a.txt".

It's also important to run on the Jenkins master machine by placing "a.txt" and "sysgvy.groovy" onto Jenkins master machine's workspace. Executing on slave machine does not work.

Try it, the file should be found and get read in the script without any problem.

If there is problem with variable Thread, it is just that some modules need to be imported. So add these lines to the start of code:

import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
like image 185
linbianxiaocao Avatar answered Oct 02 '22 14:10

linbianxiaocao