Jenkins Pipeline 外部脚本返回空值

标签 jenkins groovy jenkins-pipeline

我的问题类似于this one关于如何加载外部 groovy 脚本,然后在不同的 groovy 脚本中调用方法。到目前为止,我已经能够使用不返回值的方法,但我无法将返回值放入调用的变量中。

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

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

这是相关的 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

这是上述代码的完整 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

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

java.lang.NullPointerException: Cannot invoke method get_user() on null object ...

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

最佳答案

您必须使用 return this 结束您的 tools.groovy
查看此问题的答案 How do you load a groovy file and execute it

关于Jenkins Pipeline 外部脚本返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44190120/

相关文章:

groovy - Groovy 是一种需要了解的语言吗?

git - Jenkins 插件失败错误

java - Jenkins 文件 : varibale not "parsed" inside SSH command

git - 如何更新 Jenkins 中所有作业的 git 凭据?

java - 如何使用 AST 转换编译混合 java groovy 项目?

gradle - Gradle 依赖和动态变量

Jenkins Pipeline 每个分支的环境变量配置

jenkins - 如何在 Jenkins Pipeline 中指定 Clover CoverageTarget 指标?

docker - docker 中的Jenkins从属无法使用JNLP4连接

Jenkinsfile 中带有类引用的 Jenkins 共享库