2016-04-29 39 views
5

我有多個步驟的管道,例如:詹金斯通知錯誤在不同的步驟發生在管道發送郵件(前稱爲工作流)

stage 'dev - compile' 
node('master') { 
    //do something 
} 

stage 'test- compile' 
node('master') { 
    //do something 
} 

stage 'prod- compile' 
node('master') { 
    //do something 
} 

我要發一個電子郵件,如果出現錯誤的這份工作,我怎麼能發送電子郵件無論身在何處得到觸發錯誤,是這樣的:

try { 
/** 
    all the code above 
    **/ 
} catch(Exception e) { 
    mail the error 
} 
+0

[使用詹金斯'梅勒內管道的工作流程]的可能的複製(http://stackoverflow.com/questions/37169100/use-jenkins-mailer-inside-pipeline-workflow) –

回答

2

我做了什麼,包括有用的信息在我的郵件關於失敗:

try { 
    stage 'checkout cvs' 
    node('master') { 
     /** CODE **/ 
    } 

    stage 'compile' 
    node('master') { 
     /** CODE **/ 
    } 

    stage 'test unit' 
    node('master') { 
     /** CODE **/ 
    } 

    stage 'package' 
    node('master') { 
     /** CODE **/ 
    } 

    stage 'nexus publish' 
    node('master') { 
     /** CODE **/ 
    } 

    stage 'Deploy to App Server' 
    node('master') { 
     /** CODE **/    
    } 

} catch(e) { 
    String error = "${e}"; 
    // Make the string with job info, example: 
    // ${env.JOB_NAME} 
    // ${env.BUILD_NUMBER} 
    // ${env.BUILD_URL} 
    // and other variables in the code 
    mail bcc: '', 
     cc: '', 
     charset: 'UTF-8', 
     from: '', 
     mimeType: 'text/html', 
     replyTo: '', 
     subject: "ERROR CI: Project name -> ${env.JOB_NAME}", 
     to: "${mails_to_notify}", 
     body: "<b>${pivote}</b><br>\n\nMensaje de error: ${error}\n\n<br>Projecto: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}"; 
    error "${error}" 
} 
+0

這也會在您中止作業時發送電子郵件。 –

+1

這就是我想要的,我的意思是如果有東西給我一個錯誤,所以通知錯誤 –

3

那麼,你的想法是絕對正確的,你只需要catch塊之後移動mail或使用finally。例如(在僞代碼):

try { 
    //code 
    email = 'success' 
} catch(Exception e) { 
    // error handler: logging 
    email = 'failure' 
} 
send email 

或者用相同的方法對catchError管道內置:

result = 'failure' 
catchError { // this catches all exceptions and set the build result 
    //code 
    result = 'success' // we will reach this point only if no exception was thrown 
} 
send result 

或者使用finally

try { 
    //code 
} finally { 
    send email 
} 
+0

我想如果我使用finally,我會一直髮送電子郵件,我只是想通知它什麼時候修復它的中斷。另外,我嘗試了catchError {echo'ERROR MY FRIEND'; }我把一些錯誤的IP在GIT中,我沒有得到我的回聲'錯誤我的朋友' –

+0

我可能誤解你的問題。如果您只想在發生錯誤時發送電子郵件,則您的初始代碼段完全適合。至於'catchError',它不會阻止任何日誌記錄。 – izzekil

+0

我會嘗試我的代碼,我不是老實說,我只是認爲這不起作用 –

3

我認爲這是使用詹金斯建立post section而不是使用嘗試捕捉更好的辦法:

pipeline { 
    agent any 
    stages { 
     stage('whatever') { 
     steps { 
      ... 
     } 
     } 
    } 
    post { 
     always { 
      step([$class: 'Mailer', 
      notifyEveryUnstableBuild: true, 
      recipients: "[email protected]", 
      sendToIndividuals: true]) 
     } 
     } 
    } 
    } 
} 
+0

好抓!我希望我明白爲什麼Mailer插件不會在聲明式管道中更好地顯示,而不是需要更多彙編的較低級別的mail()。可能有95%的用戶對Mailer插件生成的電子郵件感到滿意...... – Yeroc