Read file from Jenkins workspace using System groovy script

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

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

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

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

Thanks!

+6
source share
2 answers

Each assembly has a workspace, so you need to find the right project first. (The terms β€œwork” and β€œproject” are used relatively interchangeably in Jenkins - also in the API.)

After that, you can either cross your fingers and simply call getWorkspace() , which is deprecated (see JavaDoc ).

Or you can find a specific assembly (e.g. the last one) that can provide you with the workspace used for that particular assembly using the getWorkspace() method, as defined in the AbstractBuild class.

Code example:

 Jenkins.instance.getJob('<job-name>').lastBuild.workspace; 
+8
source

If you have a file called "a.txt" in your workspace, as well as a script called "sysgvy.groovy" that you want to run as a groovy script system. Suppose your "sysgvy.groovy" script should read the file "a.txt".

The problem with this question is that if your script reads "a.txt" directly without providing any path, "sysgvy.groovy" executes and throws an error saying that it cannot find "a.txt".

I tested and found that the following method works well.

 def build = Thread.currentThread().executable 

Then use

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

as a complete location string to replace "a.txt".

It is also important to start the Jenkins master machine by placing "a.txt" and "sysgvy.groovy" in the workspace of the Jenkins master machine. Execution on a slave machine does not work.

Try it, you need to find and read the file in the script without any problems.

If there is a problem with the Thread variable, you just need to import some modules. Therefore, add these lines to the beginning of the code:

 import jenkins.* import jenkins.model.* import hudson.* import hudson.model.* 
+7
source

All Articles