如何使用Jenkins Pipeline插件实现Post-Build阶段?

luk*_*a5z 49 jenkins jenkins-workflow jenkins-pipeline

在阅读了解释Pipeline插件的Jenkins 教程后,似乎插件应该可以实现Post-Build步骤.但是,文档在具体说明方面相当有限.

例如,我想知道如何实现:

  • 仅在构建成功时运行
  • 仅在构建成功或不稳定时运行
  • 无论构建结果如何都运行

(我注意到最终的构建状态被设置为SUCCESS,即使某些阶段,即'build'在基于最后阶段设置时失败了.这是否意味着最终构建状态需要明确设置,即currentBuild.result = 'UNSTABLE'?)

小智 37

最好的方法是在管道脚本中使用post build action.

处理失败
声明性管道默认通过其post部分支持强大的故障处理,允许声明许多不同的"后置条件",例如:始终,不稳定,成功,失败和更改."管道语法"部分提供了有关如何使用各种后置条件的更多详细信息.

Jenkinsfile(声明性管道)

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                sh 'make check'
            }
        }
    }
    post {
        always {
            junit '**/target/*.xml'
        }
        failure {
            mail to: team@example.com, subject: 'The Pipeline failed :('
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该文档位于https://jenkins.io/doc/book/pipeline/syntax/#post下面

  • 当我在Pipeline项目中运行它时,这对我不起作用 (5认同)

小智 5

如果您正在使用 try/catch 并且您希望将构建标记为不稳定或失败,那么您必须使用 currentBuild.result = 'UNSTABLE' 等。我相信某些插件(如 JUnit Report 插件)会在发现失败时为您设置此项在junit结果中进行测试。但在大多数情况下,如果您发现错误,您必须自己设置。

如果您不想继续,第二个选项是重新抛出错误。

stage 'build'
... build
try {
    ... tests
} catch(err) {
    //do something then re-throw error if needed.
    throw(err)
}
stage 'post-build'
...
Run Code Online (Sandbox Code Playgroud)


Wil*_*ill 5

FWIW,如果您使用的是脚本化管道而不是声明性管道,则应try/catch/finally按照其他答案中的建议使用块。在finally块中,如果您想模仿声明式管道的作用,您可以将以下内容直接放入块中,或者将其设为一个函数并从您的finally块中调用该函数:

def currResult = currentBuild.result ?: 'SUCCESS'
def prevResult = currentBuild.previousBuild?.result ?: 'NOT_BUILT'

// Identify current result
boolean isAborted = (currResult == 'ABORTED')
boolean isFailure = (currResult == 'FAILURE')
boolean isSuccess = (currResult == 'SUCCESS')
boolean isUnstable = (currResult == 'UNSTABLE')

boolean isChanged = (currResult != prevResult)
boolean isFixed = isChanged && isSuccess && (prevResult != 'ABORTED') && (prevResult != 'NOT_BUILT')
boolean isRegression = isChanged && currentBuild.resultIsWorseOrEqualTo(prevResult)

onAlways()
if (isChanged) {
    onChanged()
    if (isFixed) {
        onFixed()
    } else if (isRegression) {
        onRegression()
    }
}
if (isSuccess) {
    onSuccess()
} else {
    if (isAborted) {
        onAborted()
    }
    onUnsuccessful()
    if (isFailure) {
        onFailure()
    }
    if (isUnstable) {
        onUnstable()
    }
}
onCleanup()

Run Code Online (Sandbox Code Playgroud)

各种onXYZ()调用是您定义来处理特定条件的函数,而不是使用更好的声明性post块语法。