Question

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!

Was it helpful?

Solution 2

Each build has a workspace, so you need to find the desired project first. (The terms "job" and "project" are used rather interchangeable in Jenkins - also in the API.)

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

Or you can find a specific build (e.g. the last), which can give you the workspace used for that specific build via the getWorkspace() method as it is defined in the AbstractBuild class.

Example code:

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

OTHER TIPS

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.*

Just use

build.workspace

The "build" variable is available keyword in System Groovy Script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top