jenkins2 pipeline插件的10個最佳實踐


jenkins pipeline的10個最佳實踐。

文章來自:http://www.ciandcd.com
文中的代碼來自可以從github下載: https://github.com/ciandcd

翻譯自:https://www.cloudbees.com/blog/top-10-best-practices-jenkins-pipeline-plugin

 

1. 使用最新的jenkins pipeline插件Jenkins Pipeline suite of plugins, 而不使用舊的類似功能插件,例如不使用舊的build pipeline plugin 或者舊的buildflow plugin。

新的pipeline插件是完全不同於舊的插件,新的pipeline job不同於舊的freestyle job,新的pipeline job可以不受jenkins master重啟的影響,可以暫停重啟。 新的pipeline job還可以實現更復雜的持續發布流程。

更多pipeline的學習,可以參考 https://jenkins.io/solutions/pipeline/

 

2.  通過groovy腳本實現pipeline

使用groovy實現的pipeline流程,可以將對應的groovy腳本存儲在文件Jenkinsfile, 且實現與源代碼一起的版本控制。

Jenkinsfile與源代碼一起版本控制,使得整個pipeline流程和源代碼一起可重現。 通過Jenkinsfile實現的pipeline job,可以更容易地支持多個分支multi-branch, 更容易地支持組織和團隊(GitHub organiztion and BitBucket Team)里的多個項目。

最好在groovy腳本Jenkinsfile的第一行增加#!groovy​, 使得各種ide工具或web page能夠支持groovy的語法高亮。

 

3. 盡可能地在stage里實現所有的任務

所有pipeline里非配置的任務最好在stage塊里實現。通過stage使得pipeline里所有的任務被組織為多個stage,每個stage都是一組相關的任務。

例如:

stage 'build'

//build

stage 'test'

//test

pipeline view 插件使得 pipeline的stage的view和monitor更加的清楚。

 

4. 所有資源消耗的操作都應該放到node上執行

默認地,Jenkinsfile里的腳本在jenkins master上執行,如果資源消耗的操作都在master上執行的話將影響jenkins master的運行。 所以任何資源消耗的操作都應該放到node中被分布到agent上執行,例如從git server clone代碼,java代碼的編譯等都應該在node中執行。

stage 'build'
node{
    checkout scm
    sh 'mvn clean install'
}

 

5. 盡可能地使用parallel來使得任務並行地執行

將任務並行后,使得整個job的流程更夠更快地完成,開發人員能夠更早地得到結果。

parallel 'shifting':{
    //everything
}, 'left':{
    //I can
}

對於unit的並行執行,可以查看插件Parallel Test Executor plugin,更多詳細介紹查看Parallel Test Execution on the CloudBees Blog

 

6. 並行的任務運行在不同的node上

對於並行的任務使用不同的node,使得並行的任務不相互影響,能夠實現真正的並行執行。

parallel 'integration-tests':{
    node('mvn-3.3'){ ... }
}, 'functional-tests':{
    node('selenium'){ ... }
}

 

7. 不要在node里使用input

input 能夠暫停pipeline的執行等待用戶的approve(自動化或手動),通常地approve需要一些時間等待用戶相應。 如果在node里使用input將使得node本身和workspace被lock, 不能夠被別的job使用。

所以一般在node外面使用input。

stage 'deployment'
input 'Do you approve deployment?'
node{
    //deploy the things
}

 

8. inputs應該封裝在timeout中。

pipeline可以很容易地使用timeout來對step設定timeout時間。對於input我們也最好使用timeout。

timeout(time:5, unit:'DAYS') {
    input message:'Approve deployment?', submitter: 'it-ops'
}

 

9. 應該使用withEnv來修改環境變量

不建議使用env來修改全局的環境變量,這樣后面的groovy腳本也將被影響。

一般使用withEnv來修改環境變量,變量的修改只在withEnv的塊內起作用。

withEnv(["PATH+MAVEN=${tool 'm3'}/bin"]) {
    sh "mvn clean verify"
}

 

10.盡量使用stash來實現stage/node間共享文件,不要使用archive

在stash被引入pipeline DSL前,一般使用archive來實現node或stage間文件的共享。 在stash引入后,最好使用stash/unstash來實現node/stage間文件的共享。例如在不同的node/stage間共享源代碼。

archive用來實現更長時間的文件存儲。

stash excludes: 'target/', name: 'source'
unstash 'source'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM