如何将 Jenkins 函数的值返回到构建阶段?

jk1*_*093 4 continuous-integration jenkins jenkins-groovy jenkins-pipeline

我想将 groovy 函数的值返回到我的 jenkins 构建阶段,以便该值可以用作其他阶段的条件。我不知道如何实现这一点。我尝试过类似下面的方法,但没有成功。

我的 Jenkinsfile 是这样的:

pipeline
{
  agent any
  stages
  {
       stage('Sum')
       {
         steps
         {
          output=sum()
          echo output
         }
       }
       stage('Check')
       {
         when
         {
          expression
          {
           output==5
          }
         }
         steps
         {
          echo output
         }
       }
  }
}

def sum()
{
   def a=2
   def b=3
   def c=a+b
   return c
}
Run Code Online (Sandbox Code Playgroud)

上面的方法行不通。有人可以提供正确的实施吗?

mke*_*erz 5

您缺少一个script-step。如果您想在 Jenkinsfile 中执行普通的 groovy,这是必要的。此外,output如果您想稍后访问它,则必须将其设置为全局变量。

def output // set as global variable
pipeline{
...

stage('Sum')
{
    steps
    {
        script
        {
            output = sum()
            echo "The sum is ${output}"
        }
    }
}
...
Run Code Online (Sandbox Code Playgroud)