如何在构建恢复时在Jenkins管道中发送通知?

Joo*_*imm 12 notifications jenkins jenkins-pipeline

我希望在作业恢复时从我的Jenkins管道构建发送通知.当前构建成功并且最后一次构建错误(失败,中止等)时的含义.

我知道如何发送通知.我想我的问题归结为如何检查以前版本的状态,但我可能会弄错.

我试过"currentBuild.rawBuild.getPreviousBuild()?.getResult()",但得到了异常"org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:脚本不允许使用方法org.jenkinsci.plugins.workflow.support. steps.build.RunWrapper getRawBuild".如果我关闭沙箱,它应该工作.沙箱可以吗?

Kol*_*lky 19

我找到了另一个有效的解决方案,它不需要您手动跟踪构建结果.虽然,它需要使用脚本元素:(

pipeline {
  agent any
  post {
    success {
      script {
        if (currentBuild.getPreviousBuild() && 
            currentBuild.getPreviousBuild().getResult().toString() != "SUCCESS") {
          echo 'Build is back to normal!'
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


mac*_*3zr 10

有趣的问题.您可以使用post {}部分的"已更改"部分在Jenkins声明性管道中执行此操作.但是您需要在作业中将currentBuild.result设置为SUCCESS或FAILURE,并在post部分中进行检查.就Jenkins而言,似乎没有一种简单的方法可以获得当前的构建状态(失败,成功等),而无需在管道中跟踪它 - 除非我错过了一些微妙的东西.下面是一个示例,您将在更改的部分中发送通知,以检查SUCCESS:

pipeline {
    agent any

    parameters {
        string(name: 'FAIL',     defaultValue: 'false', description: 'Whether to fail')
    }

    stages {
        stage('Test') {

            steps {

                script {

                    if(params.FAIL == 'true') {
                        echo "This build will fail"
                        currentBuild.result = 'FAILURE'
                        error("Build has failed")
                    }
                    else {
                        echo "This build is a success"
                        currentBuild.result = 'SUCCESS'
                    }

                }
            }
        }
    }

    post {
        always  {
            echo "Build completed. currentBuild.result = ${currentBuild.result}"
        }

        changed {
            echo 'Build result changed'

            script {
                if(currentBuild.result == 'SUCCESS') {
                    echo 'Build has changed to SUCCESS status'
                }
            }
        }

        failure {
            echo 'Build failed'
        }

        success {
            echo 'Build was a success'
        }
        unstable {
            echo 'Build has gone unstable'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

- 法案