How to use @Library in an imported groovy script in Jenkins declarative pipeline?

亡梦爱人 提交于 2019-12-12 07:18:52

问题


What I have is a following:

  1. global shared library created as described here. Nothing special, one script in vars folder called deleteFile.groovy, tried it - works. Library is called myOneLib
  2. a pipeline script called 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. a pipeline script called caller.groovy that is calling 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")
                }
            }
        }
    }
}

Now, when I run the build like this, I get the following error:

ERROR: Could not find any definition of libraries [myOneLib]

but when I simply move the line @Library('myOneLib') _ to the top of caller.groovy everything works.

So my question is how do use the @Library in the imported/included script? Or is there some other way to specify the global library?

Few more notes: caller.groovy and firstPipe.groovy are in the same git repo, and if I eliminate usage of the global library, everything works fine. I'm using declarative pipeline and would like to continue to do so.


回答1:


For this use case, it will make more sense to use the library step to dynamically load it at runtime.

In your firstPipe.groovy you could do something like:

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

See the Loading libraries dynamically section of the Extending with Shared Libraries documentation.



来源:https://stackoverflow.com/questions/45306383/how-to-use-library-in-an-imported-groovy-script-in-jenkins-declarative-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!