如何获取当前的 Jenkins 流水线 StepContext

How to get the current Jenkins pipeline StepContext

我在从上下文中提取对象并使用它们的管道中有一个步骤。但是,我需要访问步骤之外的那些对象以提供给不同的步骤,而第二步不会公开它。

stage() {
  steps {
    script {
        def status = waitForQualityGate()
        // Use the taskId
      }
    }
  }
}

waitForQualityGate() 仅调用 returns 布尔值,因此我无法在那里访问它。

我可以改为手动初始化步骤,如下所示:

 script {
    def qualityGate = new WaitForQualityGateStep()
    def taskId = qualityGate.getTaskId()
 }

taskId 为空。如果我尝试 运行 在步骤中手动启动方法:

script {
    def qualityGate = new WaitForQualityGateStep()
    qualityGate.start().start()
    def taskId = qualityGate.getTaskId()
}

失败并显示消息:

java.lang.IllegalStateException: you must either pass in a StepContext to the StepExecution constructor, or have the StepExecution be created automatically

WaitForQualityGateStep 有我需要的信息,但如果没有 StepContext(它是一个抽象 class)我无法初始化它。我怎样才能从管道中得到一个?

您可以在管道之前定义变量,并在步骤中设置它的值。这样变量在整个管道中都是可见的。

我仍然不知道如何手动获取步骤上下文以手动执行步骤,但如果其他人通过尝试从 Sonar 插件中获取信息而发现此问题,这就是我获取任务 ID 的方式我需要。

def output = sh(script: "mvn sonar:sonar", returnStdout: true)
echo output  // The capture prevents printing to console

def taskUri = output.find(~'/api/ce/task\?id=[\w-]*')