Jenkins共享库:无法导入软件包“无此属性”

时间:2019-09-20 13:51:35

标签: jenkins groovy jenkins-pipeline

我有一个文件可以像这样动态加载库

def lib=library(identifier: 'pipeline-core@master', retriever: modernSCM(
  [$class: 'GitSCMSource',
       remote: 'https://scm.intra/scm/jenins/pipeline-core.git',
       credentialsId: 'bitbucket.service.user'
])).ch.swisscard.pipeline.util.Utils

defaultCdPipeline {}

defaultCdPipeline是詹金斯管道定义,它使用Utils类,如

import ch.mycompany.jenkins.pipeline.util.*
...
Utils.isRunning()
...

文件结构是这样的:

+- src
|  +- mycompany
|     +- jenkins
|        +- pipeline
|           +- util
|              +- Utils.groovy
|              +- Commons.groovy
+- vars
   +- defaultCdPipeline.groovy

到目前为止有效。当我查看动态导入时,我会使用lib而不是lib.isRunning()来使用Utils.isRunning(),但这会产生以下错误

No such property: lib for class: groovy.lang.Binding

为什么?展望未来,我想同时使用Utils.groovyCommons.groovy。我将按照the example所示“预选软件包”,因此仅使用.ch.swisscard.pipeline.util

def lib=library(identifier: 'pipeline-core@master', retriever: modernSCM(
  [$class: 'GitSCMSource',
       remote: 'https://scm.intra/scm/jenins/pipeline-core.git',
       credentialsId: 'bitbucket.service.user'
])).ch.swisscard.pipeline.util

defaultCdPipeline {}

但是,这也不能作为呼叫lib.Uils.isRunning()

...
   stages {
      stage('Deployment') {
         steps {
            script {
               lib.Uils.isRunning()`
...

抛出与上述相同的异常

No such property: lib for class: groovy.lang.Binding

Utils的内容

package ch.mycompany.jenkins.pipeline.util

class Utils implements Serializable {

    @NonCPS
    def static String isRunning() {
        return "isRunning()"
    }
}

有人可以阐明这个问题,并告诉我如何正确加载一个包/多个类吗?

1 个答案:

答案 0 :(得分:0)

您应该只这样声明库加载:

def lib = library(
    identifier: 'pipeline-core@master', retriever: modernSCM
    (
        [
            $class: 'GitSCMSource',
            remote: 'https://scm.intra/scm/jenins/pipeline-core.git',
            credentialsId: 'bitbucket.service.user'
        ]
    )
)

假设这是常规类:

package ch.mycompany.jenkins.pipeline.util

class Utils implements Serializable
{
    @NonCPS
    def static String isRunning()
    {
        return "isRunning()";
    }

    def String isItReallyRunning()
    {
        return "isItReallyRunning()";
    }
}

然后调用这样的静态方法:

lib.ch.mycompany.jenkins.pipeline.util.Utils.isRunning();

和这样的实例方法:

// call the constructor (you can also call a constructor with parameters)
def utils = lib.ch.mycompany.jenkins.pipeline.util.Utils.new();

// call your instance method
utils.isItReallyRunning();