2017-10-09 83 views
0

沒有太多的編程經驗,但很高興學習。jenkinsfile在Groovy腳本中加載局部變量

問題:將jenkinsfile構建錯誤數據發送到mattermost在文件中工作得很好,但是當作爲.groovy腳本加載時,它會「靜靜地」失敗。有關爲什麼/如何將這些信息發佈到加載的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 

注:

  • curlBuildFailed.groovy的內容放入同樣的 位置,因爲load "ci/curlBuildFailed.groovy"會創建所需的 輸出。
  • 已將範圍縮小到${err}curlBuildFailed.groovy,只要我刪除該變量,它會發帖 以mattermost就好了。
  • (我們有與此類似這樣試圖抽象重複的代碼到一個更易於維護結構約30 ansible角色)
  • 有四處搜尋了幾個小時,似乎與這些類似的,但我還沒有找到一個尚未解決:
  • jenkins plain catch blocks
  • don't think I need a 'returns this;' but who knows
  • Passing Variables in Jenkinsfile Closure

謝謝您的時間! - 山姆

回答

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 
     } 
    } 
} 
相關問題