如何在Jenkins声明性管道中导入的groovy脚本中使用@Library?

时间:2017-07-25 14:32:33

标签: jenkins groovy jenkins-pipeline

我所拥有的是以下内容:

  1. 按照描述here创建的全局共享库。没有什么特别的,名为vars的{​​{1}}文件夹中的一个脚本尝试了它 - 有效。库名为deleteFile.groovy
  2. 名为myOneLib
  3. 的管道脚本
    firstPipe.groovy
    1. 一个名为@Library('myOneLib') _ def execute(String zCmakeListsPath){ stage('some kind of stage 2') { echo "Hello from stage 1 with " + zCmakeListsPath echo "var attempt ${env.mySrcDir}" } stage('second stage'){ echo "and one from stage 2" echo "param was " + zCmakeListsPath echo "var attempt ${env.myBuildDir}" //call function from global lib deleteFile 'for 3rd party global library now' } } return this的管道脚本,正在调用caller.groovy
    2. firstPipe.groovy

      现在,当我像这样运行构建时,我收到以下错误:

        

      错误:找不到库[myOneLib]

      的任何定义

      但是当我将pipeline { agent any environment { myBuildDir = "thisShoulbBeBuild" mySrcDir = "andHereIsSrc" } stages { stage('first') { steps { script{ echo 'beggining with ' + myBuildDir def rootDir = pwd() echo 'rootDir is ' + rootDir def example = load "${rootDir}/fullPipe/firstPipe.groovy" example.execute("rasAlGhul") } } } } }行移到@Library('myOneLib') _的顶部时,一切正常。

      所以我的问题是如何在导入/包含的脚本中使用caller.groovy?或者是否有其他方法来指定全局库?

      更多注释:@Librarycaller.groovy属于同一个git仓库,如果我不使用全局库,一切正常。我正在使用声明性管道,并希望继续这样做。

1 个答案:

答案 0 :(得分:4)

对于这个用例,使用library步骤在运行时动态加载它会更有意义。

在您的firstPipe.groovy中,您可以执行以下操作:

final myOneLib = library('myOneLib')

def execute(String zCmakeListsPath){
  stage('some kind of stage 2') {
    echo "Hello from stage 1 with " + zCmakeListsPath
    echo "var attempt ${env.mySrcDir}"

  }
  stage('second stage'){
    echo "and one from stage 2"
    echo "param was " + zCmakeListsPath
    echo "var attempt ${env.myBuildDir}"
    //call function from global lib
    myOneLib.deleteFile 'for 3rd party global library now'
  }
}

return this

请参阅Loading libraries dynamically section of the Extending with Shared Libraries documentation