jenkinsfile在groovy脚本中加载局部变量

时间:2017-10-09 22:50:04

标签: groovy jenkins-pipeline mattermost

没有很多编程经验但很乐意学习。

问题:将jenkinsfile构建错误数据发送到mattermost在文件中本地工作正常,但是当作为.groovy脚本加载时,它会无声地"静默地#34;。关于为什么/如何在加载的groovy脚本中将此信息发布到通道的任何指导?

Jenkinsfile

#!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

注意:

感谢您的时间! - 山姆

1 个答案:

答案 0 :(得分: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
       }
    }
}