ALAL
ALAL

Reputation: 33

How to get workspace of jenkins pipeline plugin job (WorkflowRun object java API )

In the java API, I can access to the workspace path from the Run.java object: (Until today, all objects were instance of hudson.model.AbstractBuild)

  1. hudson.model.AbstractBuild#getWorkspace()
  2. hudson.model.Run#getExecutor().getCurrentWorkspace()

In Pipeline plugin I don’t have an access to the workspace, the run object is instance of org.jenkinsci.plugins.workflow.job.WorkflowRun and this object doesn’t link to any workspace.

this call return null: hudson.model.Run#getExecutor().getCurrentWorkspace()

how can I get it?

thank you

Upvotes: 3

Views: 5224

Answers (2)

Claas Diederichs
Claas Diederichs

Reputation: 156

Took me a while to figure it out. You can access the workspaces (as a workflow run can have multiple workspaces) from the WorkflowRun in the following way:

import org.jenkinsci.plugins.workflow.job.WorkflowRun
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import org.jenkinsci.plugins.workflow.graph.FlowGraphWalker;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.graph.StepStartNode;
import org.jenkinsci.plugins.workflow.cps.nodes.StepStartNode;
import org.jenkinsci.plugins.workflow.actions.WorkspaceAction
...
...
b = item.getLastBuild()

if (b instanceof WorkflowRun) {
  exec = b.getExecution();
  if(exec == null)
    continue;
  FlowGraphWalker w = new FlowGraphWalker(exec);
  for (FlowNode n : w) {
    if (n instanceof StepStartNode) {
      action = n.getAction(WorkspaceAction);
      if (action) {
        String node = action.getNode().toString();
        String workspace = action.getPath().toString();
      }
    }
  }
}

You now have the node and the workspace on it. This will capture workspaces acquired by the node step as well as workspaces acquired by the ws step. You probably want to store the node/workspaces, as you will most probalby get several of them on a complex pipeline.

Upvotes: 7

eyalstoler
eyalstoler

Reputation: 184

You can simply do this:

node {
  withEnv(["WORKSPACE=${pwd()}"]) {
    echo WORKSPACE
  }
}

See this reference for more info.

Upvotes: 1

Related Questions