Workspace path in job DSL within Jenkins pipeline Workspace path in job DSL within Jenkins pipeline jenkins jenkins

Workspace path in job DSL within Jenkins pipeline


I stumbled upon this because there seems to be no good way. Here is how I do it:

node {    stage('test') {        sh 'pwd > workspace.txt'        jobDsl scriptText: '''            String workspace = readFileFromWorkspace('workspace.txt').trim()            def file = new File(workspace, 'test.txt')            file.append('It worked!')'''    }}

So first grab the workspace in the pipeline script and then pass it to the job dsl. If you have more than just the workspace variable, that you need in your scripts I suggest transferring via a properties file:

node {    stage('test') {        sh 'echo "workspace="$(pwd) > build.properties'        jobDsl scriptText: '''            Properties props = new Properties();            props.load(streamFileFromWorkspace('build.properties'))            def file = new File(props.getProperty('workspace'), 'test.txt')            file.append('It worked!')'''    }}


This can be achieved by using SEED_JOB variable:

 String workspacePath = SEED_JOB.lastBuild.checkouts[0].workspace

It is described in project's wiki:

Access to the seed job is available through the SEED_JOB variable. The variable contains a reference to the internal Jenkins object that represents the seed job. The actual type of the object depends on the type of job that runs the DSL. For a freestyle project, the object is an instance of hudson.model.FreeStyleProject. See the Jenkins API Documentation for details.

The SEED_JOB variable is only available in scripts, not in any classes used by a script. And it is only available when running in Jenkins, e.g. in the "Process Job DSLs" build step.

The following example show how to apply the same quiet period for a generated job as for the seed job.

job('example') { quietPeriod(SEED_JOB.quietPeriod) }


You can use the __FILE__ variable in a Job DSL script to get the path of the current script. Maybe you can use that to derive the workspace directory. See Script Location for details.

def scriptDir = new File(__FILE__).parent.absolutePath