小编典典

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

jenkins

我有以下内容:

  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
  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")
                    }
                }
            }
        }
    }

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

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

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

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

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


阅读 783

收藏
2020-07-25

共1个答案

小编典典

对于此用例,使用该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

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

2020-07-25