【问题标题】:Jenkins pipeline - how to load a Jenkinsfile without first calling node()?Jenkins 管道 - 如何在不首先调用 node() 的情况下加载 Jenkinsfile?
【发布时间】:2019-01-02 03:10:40
【问题描述】:

我有一个有点独特的设置,我需要能够动态加载位于我正在构建的 src 之外的 Jenkinsfile。 Jenkinsfiles 本身通常调用 node() 然后是一些构建步骤。这会导致多个执行程序不必要地被吃掉,因为我需要已经调用 node() 才能使用加载步骤来运行 Jenkinsfile,或者如果我将 Jenkinsfile 作为字符串读取并执行它,则执行 groovy。

我今天在工作 UI 中的内容:

@Library(value='myGlobalLib@head', changelog=fase) _

node{
    load "${JENKINSFILES_ROOT}/${PROJECT_NAME}/Jenkinsfile"
}

加载的 Jenkinsfile 通常也会调用 node()。例如:

node('agent-type-foo'){
    someBuildFlavor{
        buildProperty = "some value unique to this build"
        someConfig = ["VALUE1", "VALUE2", "VALUE3"]
        runTestTarget = true
    }
}

这会导致在管道运行期间消耗 2 个执行器。理想情况下,我在没有先调用 node() 的情况下加载 Jenkinsfiles,但是每当我尝试时,我都会收到一条错误消息:

"Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node"

有没有办法在没有 hudson.FilePath 上下文的情况下加载 Jenkinsfile 或执行 groovy?我似乎在文档中找不到任何东西。我正准备对 Jenkinsfile 进行预处理,以删除它们对 node() 的初始调用,并使用 Jenkinsfile 使用的值调用 node(),然后加载文件的其余部分,但是,这有点太对我来说很脆弱。

【问题讨论】:

    标签: jenkins jenkins-pipeline


    【解决方案1】:

    当使用load 步骤时,Jenkins 会评估文件。您可以将 Jenkinsfile 的逻辑包装到一个函数中(在我的示例中名为 run()),以便它可以加载但不会自动运行。

    def run() {
        node('agent-type-foo'){
            someBuildFlavor{
                buildProperty = "some value unique to this build"
                someConfig = ["VALUE1", "VALUE2", "VALUE3"]
                runTestTarget = true
            }
        }
    }
    
    // This return statement is important in the end of Jenkinsfile
    return this 
    

    像这样从你的工作脚本中调用它:

    def jenkinsfile
    node{
        jenkinsfile = load "${JENKINSFILES_ROOT}/${PROJECT_NAME}/Jenkinsfile"
    }
    jenkinsfile.run()
    

    这样就没有更多嵌套的node 块了,因为第一个块在run() 函数被调用之前就被关闭了。

    【讨论】:

    • 谢谢,我最终做了一些非常相似的事情,但尝试先加载文件而不调用 node() 并捕获 MissingContextVariableException 异常。如果该异常被捕获,我调用 node() 并尝试再次加载文件。这给了我们更多的灵活性。
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多