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

can*_*Now 5 groovy jenkins jenkins-pipeline

我有以下内容:

  1. 作为全球描述共享库创建这里。没什么特别的,vars文件夹中的一个脚本名为deleteFile.groovy,可以尝试-工作。图书馆被称为myOneLib
  2. 名为 firstPipe.groovy
@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
Run Code Online (Sandbox Code Playgroud)
  1. caller.groovy调用的管道脚本正在调用firstPipe.groovy
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")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

错误:找不到库的任何定义[myOneLib]

但是当我简单地将行移动@Library('myOneLib') _caller.groovy所有工作的顶部时。

所以我的问题是如何@Library在导入/包含的脚本中使用?还是有其他方法可以指定全局库?

很少有其他注释:caller.groovy并且firstPipe.groovy都在同一个git repo中,如果我取消使用全局库,一切都会很好。我正在使用声明性管道,并且希望继续这样做。

mko*_*bit 6

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

在你的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
Run Code Online (Sandbox Code Playgroud)

请参阅使用共享库扩展文档的动态加载库部分