如何从另一个 Jenkinsfile 调用 Jenkinsfile 或 Jenkins 作业?

时间:2021-04-20 08:22:16

标签: jenkins groovy jenkins-pipeline

在用 Groovy 编写的 脚本化管道上,我有 2 个 Jenkinsfile,分别是 - Jenkinsfile1Jenkinsfile2

是否可以从 Jenkinsfile2 调用 Jenkinsfile1

假设以下是我的Jenkinsfile1

#!groovy

stage('My build') {
    node('my_build_node') {
        def some_output = True
        if (some_output) {
            // How to call Jenkinsfile2 here?
        }
    }
}

当输出的值不为空时,如何调用上面的 Jenkinsfile2

或者是否可以调用另一个使用 Jenkinsfile2 的 Jenkins 作业

2 个答案:

答案 0 :(得分:4)

你的问题对我来说不是很清楚。如果您只想加载和评估一些 Groovy 代码到您的代码中,您可以使用 load()(如 @JoseAO 之前所述)。除了他的例子,如果你的文件 (Jenkinsfile2.groovy) 有一个 call() 方法,你可以直接使用它,就像这样:

node('master') {
    pieceOfCode = load 'Jenkinsfile2.groovy'
    pieceOfCode()
    pieceOfCode.bla()
}

现在,如果您想触发另一个作业,您可以使用 build() 步骤,即使您没有使用声明性管道。问题是您正在调用的管道必须在 Jenkins 中创建,因为 build() 将作业名称作为参数,而不是管道文件名。下面是如何调用名为 pipeline2 的作业的示例:

node('master') {
    build 'pipeline2'
}

现在,至于您的问题“当输出的值不为空时,我如何在上面调用 Jenkinsfile2?”,如果我理解正确,您正在尝试运行一些 shell 命令,如果它为空,则您'将加载 Jenkinsfile/管道。实现方法如下:

// Method #1
node('master') {
    try {
        sh 'my-command-goes-here'
        build 'pipeline2' // if you're trying to call another job
        
        // If you're trying to load and evaluate a piece of code
        pieceOfCode = load 'Jenkinsfile2.groovy'
        pieceOfCode()
        pieceOfCode.bla()       
    }
    catch(Exception e) {
        print("${e}")
    }
}

// Method #2
node('master') {
    def commandResult = sh script: 'my-command-goes-here', returnStdout: true

    if (commandResult.length() != 0) {
        build 'pipeline2' // if you're trying to call another job
        
        // If you're trying to load and evaluate a piece of code
        pieceOfCode = load 'Jenkinsfile2.groovy'
        pieceOfCode()
        pieceOfCode.bla()       
    }
    else {
        print('Something went bad with the command.')
    }
}

最好的问候。

答案 1 :(得分:0)

例如,您的 Jenkisfile2 是我的“pipeline2.groovy”。

    def pipeline2 = load (env.PATH_PIPELINE2 + '/pipeline2.groovy')
    pipeline2.method()