Jenkins Pipeline 外部脚本返回空值

jmr*_*cha 2 groovy jenkins jenkins-pipeline

我的问题与此类似,关于如何加载外部 groovy 脚本,然后在不同的 groovy 脚本中调用其中的方法。到目前为止,我已经能够获得不返回值的方法,但我在将返回值获取到被调用的变量中时遇到问题。

例如,以下管道代码可以工作,但在我运行 Jenkins 管道时给出了nullfor值。$build_user它实际上并没有返回我期望的结果,我也不知道为什么。

node {
    stage('test') {
        def tools = load "/var/lib/jenkins/workflow-libs/vars/tools.groovy"
        build_user = tools.get_user()
        echo "build_user: $build_user"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是相关内容tools.groovy的样子。

def exampleMethod() {
    // Do stuff
}

// Try to get a build username
def get_user() {

    try {
        wrap([$class: 'BuildUser']) {
            // Set up our variables
            fallback_user = 'GitHub'
            github_user = BUILD_USER
            commit_author = 'Test1'

            // Try to use Jenkins build user first
            if (github_user) {
                echo "using github_user: $github_user"
                return github_user
            }
            // Otherwise try to use commit author
            else if (commit_author) {
                echo "using commit_author: $commit_author"
                return commit_author
            }
            // Otherwise username is blank so we use the default fallback
            else {
                echo "using fallback: $fallback_user"
                return fallback_user
            }
        }
    }
    catch (err) {
        // Ignore errors
    }

    echo "Done."
}

return this
Run Code Online (Sandbox Code Playgroud)

以下是上述代码的完整 Jenkins 输出。

Started by user XXX
[Pipeline] node
Running on master in /var/lib/jenkins/workspace/test
[Pipeline] {
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] load
[Pipeline] { (/var/lib/jenkins/workflow-libs/vars/tools.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] wrap
[Pipeline] {
[Pipeline] echo
using github_user: XXX
[Pipeline] }
[Pipeline] // wrap
[Pipeline] echo
Done.
[Pipeline] echo
build_user: null
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)

return this如果我最后删除并在 Jenkins 中抛出以下错误,则上述方法根本不起作用。

java.lang.NullPointerException:无法在 null 对象上调用方法 get_user() ...

我究竟做错了什么?我怀疑我错过了一些简单的东西,但我对 Groovy 不太熟悉,所以我不确定它可能是什么。

has*_*chi 6

你必须以 结束你tools.groovyreturn this
请参阅此问题的答案How do you load a groovy file andexecute it