【问题标题】:How to use @Library in an imported groovy script in Jenkins declarative pipeline?如何在 Jenkins 声明性管道的导入 groovy 脚本中使用 @Library?
【发布时间】:2017-07-25 14:32:33
【问题描述】:

我有以下内容:

  1. 按照here 所述创建全局共享库。没什么特别的,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.groovyfirstPipe.groovy 在同一个 git 存储库中,如果我不使用全局库,一切正常。我正在使用声明式管道,并希望继续这样做。

【问题讨论】:

  • 使用library 步骤在导入的脚本中动态加载可能更容易处理一些与 Jenkins Groovy 运行时工作方式有关的奇怪问题。
  • @mkobit 非常感谢您的提示,我不敢相信我错过了jenkins.io/doc/book/pipeline/shared-libraries/… 你会宣传你的评论来回答吗?还是我的问题太简单明了,我应该删除它? :)

标签: jenkins groovy jenkins-pipeline


【解决方案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

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

【讨论】:

  • 如果我使用低于 2.7 的 Jenkins Pipeline 版本,是否有任何解决方法?
  • @VitaliiVitrenko 我假设你在谈论Pipeline Shared Groovy Libraries Plugin,但我想不出一个优雅的。您可以要求用户在其管道中使用@Library 将其置于类路径中,或者将这些方法或类传递到其他级别。这些只是看起来像 hacky 的解决方法。
猜你喜欢
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多