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

我是研究僧i 提交于 2019-12-11 05:19:18

问题


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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!