你能在一个 Jenkins 阶段加载一个 groovy 文件吗? 运行 函数;并在多个 Jenkins 阶段使用 @groovy.transform.Field 共享数据

Can you load a groovy file in one Jenkins stage; run functions; and share data using a @groovy.transform.Field across multiple Jenkins stages

假设您有一个 groovy 文件:

@groovy.transform.Field
def data = [:]

def function1() {
    data.put(5)
}

def function2() {
    data.each {num} ->
    println("${num}")
}

return this

并且您想调用以下 Jenkinsfile 中的函数;你可以在一个阶段加载 groovy 文件,将加载的文件传递给第二阶段并调用一个函数吗?我尝试了以下方法:

pipeline {
    stage('One') {
      steps {
        script {
            def rootDir = pwd()
            def script = load "${rootDir}/script.groovy"
            script.function1()
        }
      }
    }
    stage('Two') {
      steps {
        script {
            script.function2()
        }
      }
    }
}

您确实可以实现这一点,因为 Documentation 适用。

为了使其在声明性管道中工作,您只需将 script 参数定义为全局参数,以便在其他步骤中访问它:

pipeline {
   stage('One') {
     steps {
        script {
           def rootDir = pwd()
           // Don't use 'def' here - so it will be a global variable
           script = load "${rootDir}/script.groovy" 
           script.function1()
       }
     }
   }
   stage('Two') {
      steps {
        script {
            script.function2()
       }
     }
   }
}

为了便于阅读,您还可以将其定义为 pipeline 范围之外的全局参数:

def script

pipeline {
   ...
}