Jenkins 管道正在跳过 groovy 'else if' 子句

ARL*_*ARL 2 groovy jenkins jenkins-groovy jenkins-pipeline

我正在我的管道中进行一些测试。我的目标是,如果存在错误文件,则构建应该失败。但是如果由于某种原因测试遇到异常并且没有写入错误或成功的文件,管道也应该失败。如果失败的条件都不满足,我希望上游作业执行。

我在舞台上写的,最初看起来是这样的:

stage('system tests') {
    steps {
        dir(project_root) {
            def error_exists = sh(
                script: 'ls error.txt', returnStatus: true
            )
            if (error_exists == 0) {
                currentBuild.result = 'FAILED'
                return
            }
            build job: 'my-job;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码有效。当正在执行的测试写入错误文件时,管道将失败。然后我尝试修改代码以适应既没有写入错误文件也没有写入成功文件的结果。

stage('system tests') {
    steps {
        dir(project_root) {
            def error_exists = sh(
                script: 'ls error.txt', returnStatus: true
            )
            def success_exists = sh(
                script: 'ls success.txt', returnStatus: true
            )
            if (error_exists == 0) {
                currentBuild.result = 'FAILED'
                return
            } else if (success_exists == 1 && error_exists == 1) {
                currentBuild.result = 'FAILED'
                return
            }
            build job: 'my-job;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我模拟了一种情况,既没有写入文件,管道也没有失败,而是触发了上游构建。else if如果两个 shell 脚本的结果都为假,为什么我不输入子句`?我从这里拿了逻辑运算符,我认为它们应该得到满足(下面的代码是从新作业管道中的 shell 脚本输出的)

[new-job] Running shell script
+ ls error.txt
ls: cannot access error.txt: no such file or directory

[new-job] Running shell script
+ ls success.txt
ls: cannot access success.txt: no such file or directory
Run Code Online (Sandbox Code Playgroud)

gro*_*gor 7

如果这些文件不存在,则 sh jenkins 步骤返回错误代码 2。您应该像这样重写“if 条件”:

success_exists == 2 && error_exists == 2
Run Code Online (Sandbox Code Playgroud)

但是,我认为在您的情况下,此代码更合适:

stage('system tests') {
steps {
    dir(project_root) {
        def error_exists = sh(
            script: 'ls error.txt', returnStatus: true
        )
        def success_exists = sh(
            script: 'ls success.txt', returnStatus: true
        )
        if (error_exists == 0) {
            currentBuild.result = 'FAILED'
            return
        } else if (success_exists != 0 && error_exists != 0) {
            currentBuild.result = 'FAILED'
            return
        }
        build job: 'my-job;
    }
}
Run Code Online (Sandbox Code Playgroud)

因为可能还有其他原因导致无法找到该文件(无法访问等)。