问题
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)
- hudson.model.AbstractBuild#getWorkspace()
- 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
回答1:
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.
回答2:
You can simply do this:
node {
withEnv(["WORKSPACE=${pwd()}"]) {
echo WORKSPACE
}
}
See this reference for more info.
来源:https://stackoverflow.com/questions/41922630/how-to-get-workspace-of-jenkins-pipeline-plugin-job-workflowrun-object-java-api