如何根据执行结果在Jenkins Pipeline中设置当前构建结果?

cyvaqqii  于 2022-11-21  发布在  Jenkins
关注(0)|答案(2)|浏览(323)

我写了下面的代码,想给用户发送电子邮件通知。但是我注意到有时会有“误报”报告。我只是想知道是否有一种方法Jenkins声明性管道允许我使用真实的的执行状态来设置currentBuild.result.(我想我应该使用currentBuild.result = 'SUCCESS''FAILURE')。例如,start_up.sh /mydata/test.json可以将“SUCCESSFUL”或“ERROR”写入文件。如何将currentBuild.result分别设置为“SUCCESS”或“FAILURE”?根据文件的内容,非常感谢

pipeline {

  agent {
    docker {
      image ...
      args ...
    }
  }

  parameters {
    string(name: 'E_USERNANE', defaultValue: 'githubuser', description: 'Please input the username')
    string(name: 'E_BRANCH', defaultValue: 'dev', description: 'Please input the git branch you want to test')
  }

  stages {
    stage('build') {
      steps {
        echo "username: ${params.E_USERNANE}"
        echo "branch: ${params.E_BRANCH}"
        sh """
        ...
        start_up.sh /mydata/test.json
        ...
        """
      }
    }
  }

  post {
    failure {
      // notify users when the Pipeline fails
      mail to: 'xxxi@gmail.com',
      subject: "Failed Pipeline * ${currentBuild.fullDisplayName}",
      body: "Something is wrong with ${env.BUILD_URL}."
    }
    success {
      // notify users when the Pipeline succeeds
      mail to: 'xxx@gmail.com',
      subject: "Success Pipeline * ${currentBuild.fullDisplayName}",
      body: "The build ${env.BUILD_URL} is passed!"
    }
  }
}
7rtdyuoh

7rtdyuoh1#

看起来标题(* 如何根据执行结果在Jenkins Pipeline中设置当前构建结果?)与代码示例( 如何根据该文件的内容分别将currentBuild.result设置为“SUCCESS”或“FAILURE”?*)有点不同
在像您这样的声明性管道中,可以使用catchError块根据命令执行结果轻松设置当前构建(和阶段)结果。例如,将阶段设置为FAILURE,将整个作业设置为UNSTABLE

catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
    command ...
}

我不知道有什么简洁的一行程序可以直接从文件内容设置构建/阶段结果(身体的问题)。但我想你可以在将状态消息写入文件时,应该设置start_up.sh脚本的正确退出代码,因此在将"SUCCESSFUL"写入文件时,可以使用零代码退出脚本,但是当写"ERROR"时,你可以用非零代码退出,这就足够让流水线处理catchError块了。

a11xaf1n

a11xaf1n2#

这是我在一些gitlab集成项目中使用的一个例子...但是使用的是脚本化的管道。当构建失败时会有电子邮件通知,当它恢复稳定时也会有电子邮件通知。

/* documentation pour les appels gitlab:
 https://github.com/jenkinsci/gitlab-plugin#configuring-access-to-gitlab

Toujours utiliser la syntaxe scripted pipeline (et non declarative, merci)
Please read the fucking manual:
https://github.com/jenkinsci/gitlab-plugin
*/
// Reference the GitLab connection name from your Jenkins Global configuration (http://JENKINS_URL/configure, GitLab section)

 if (env.BRANCH_NAME != 'developpement') {
      properties([gitLabConnection('numagit'),
        buildDiscarder(
            logRotator(
                numToKeepStr: '1',artifactNumToKeepStr: '1'
            )
        )
        ]
        )
    }
  else {
       properties([gitLabConnection('numagit'),
        buildDiscarder(
            logRotator(
                numToKeepStr: '5',artifactNumToKeepStr: '1'
            )
        )
    ]
)
  }

    node {
    try {
         stage('Checkout sources') {

                echo 'Checkout..'
                checkout scm
         }
         
         
         gitlabBuilds(builds: [
                            "Compiling linux64", 
                            "Compiling linux 32 bits",
                            "Compiling win32",
                            "Deploy"
                            ]) {

         
    try {
        stage('Compiling linux64') {
            gitlabCommitStatus("Compiling linux64") {
                ...
            }
        }
    } catch (e) {
       currentBuild.result = "FAILURE" // make sure other exceptions are recorded as failure too
    }
        
    stage('Compiling linux 32 bits') {
           gitlabCommitStatus("Compiling linux 32 bits") {
                 ...
                }        
        }        

        
        stage('Compiling win32') {
            gitlabCommitStatus("Compiling win32") {
              ...
                }
        }
 
 
        stage('Deploy') {
            gitlabCommitStatus("Deploy") {
             ...    
        }
       }
   
    }
         currentBuild.result = 'SUCCESS'

    } // try
    catch(all) {
        echo "Il y a eu des erreurs"
        currentBuild.result = 'FAILURE'
        notifyFailed()
    }
    finally {
     // Si le build passe de failure a normal 
        if (currentBuild.getPreviousBuild().result == 'FAILURE') {
         if (currentBuild.result == 'SUCCESS') {
                echo 'build has been fixed'
                notifyFixed()
            }
        }
    } 
    echo "RESULT: ${currentBuild.result}"

}

def notifyFixed()
{
    emailext (
            subject:"[Integration Continue] ${env.JOB_NAME} - Compilation # ${env.BUILD_NUMBER} - Build has been fixed",
            body:"""
            <p>Compilation fixed par commit ${env.GIT_COMMIT}

            "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"
            </p>
            """,
            recipientProviders:[[$class: 'DevelopersRecipientProvider'],[$class: 'CulpritsRecipientProvider']]
            )

}

def notifyFailed() {
    emailext (
            subject:"[Integration Continue] ${env.JOB_NAME} - Compilation # ${env.BUILD_NUMBER} - FAILED:",
            body:"""
            <p>
            Commit ${env.GIT_COMMIT} 
            Vérifier la sortie de la console pour voir le résultat de la compilation :
            "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"
            </p>
            """,
            recipientProviders:[[$class: 'DevelopersRecipientProvider'],[$class: 'CulpritsRecipientProvider']]
            )
}

相关问题