如何获取jenkins管道插件作业的工作区(WorkflowRun对象Java API)

如何获取jenkins管道插件作业的工作区(WorkflowRun对象Java API)

问题描述:

在Java API中,我可以从Run.java对象访问工作区路径: (直到今天,所有对象都是hudson.model.AbstractBuild的实例)

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()

在Pipeline插件中,我无权访问工作空间,运行对象是org.jenkinsci.plugins.workflow.job.WorkflowRun的实例,并且该对象未链接到任何工作空间.

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.

此调用返回null:hudson.model.Run#getExecutor().getCurrentWorkspace()

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

我如何得到它?

谢谢

花点时间找出答案. 您可以通过以下方式从WorkflowRun访问工作空间(因为工作流运行可以具有多个工作空间):

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();
      }
    }
  }
}

现在您已经有了节点和工作空间.这将捕获节点步骤获取的工作空间以及ws步骤获取的工作空间. 您可能想要存储节点/工作区,因为大多数probalby都会在复杂的管道上获得其中的几个.

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.