0

没有太多编程经验,但乐于学习。

问题:向mattermost 发送jenkinsfile 构建错误数据在文件中本地工作得很好,但是当作为.groovy 脚本加载时,它会“静默”地失败。关于为什么/如何在加载的 groovy 脚本中将此信息发布到频道的任何指导?

詹金斯文件

#!groovy
properties([[$class: 'jenkins.model.BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '5', artifactNumToKeepStr: '5']]])

node('node_name'){

    def err = null
    currentBuild.result = "SUCCESS"
    role_name = "deploy"

    try {
        timeout(60){
            stage "${role_name}"
                deleteDir()
                checkout scm
                sh 'introduce error here'
        }
    }
    catch (error){
        err = error
        currentBuild.result = "FAILURE"
        load "ci/curlBuildFailed.groovy"
    }
    finally {
        if (err){
            throw err
        }
    }
}

curlBuildFailed.groovy

sh "curl -i -X POST -d \'payload={" +
"\"text\": \"${env.JOB_NAME}: ${env.BUILD_URL} - build failed with ${err}!\", " +
"\"username\": \"JenkinsBot\", " +
"\"icon_url\": \"$FAIL_BUILD\"}\' $DEVOPS_NOTIFY_URL "

运行上面的代码会产生这个:

[cure-deploy] Running shell script
+ introduce error here
/home/jenkins/remote/workspace/blablabla/script.sh: line 2: introduce: command not found
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // timeout
[Pipeline] load
[Pipeline] { (ci/curlBuildFailed.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 127
Finished: FAILURE

笔记:

  • 将 的内容拖放到与创建所需输出 curlBuildFailed.groovy相同的位置。load "ci/curlBuildFailed.groovy"
  • 将罪魁祸首缩小到${err}in curlBuildFailed.groovy,只要我删除它发布到最重要的变量就好了。
  • (我们有大约 30 个与这个类似的 ansible 角色,因此试图将重复的代码抽象为更易于维护的结构)
  • 已经搜索了几个小时,它似乎与这些相似,但我还没有找到解决方案:
  • 詹金斯平原捕捉块
  • 不要认为我需要“退货”;但谁知道
  • 在 Jenkinsfile 闭包中传递变量

感谢您的时间!- 山姆

4

1 回答 1

0

您不需要使用 groovy 脚本向 Mattermost 发送消息。有一个 Jenkins 插件可以帮助您向 Mattermost 发送通知消息。您可以点击此链接:https ://github.com/jenkinsci/mattermost-plugin

安装和配置后,您可以使用mattermostSend发送通知。

那么您的管道将与此类似:

node('node_name') {def err = null
    currentBuild.result = "SUCCESS"
    role_name = "deploy"

    try {
        timeout(60){
            stage "${role_name}"
                deleteDir()
                checkout scm
                sh 'introduce error here'
        }
    }
    catch (error){
        err = error
        currentBuild.result = "FAILURE"
        mattermostSend color: 'danger', message: 'Message from Jenkins Pipeline', text: \"${env.JOB_NAME}: ${env.BUILD_URL} - build failed with ${err}!\"
    }
    finally {
       if (err){
          throw err
       }
    }
}
于 2018-02-12T08:28:51.327 回答