寫 pipeline 就是寫 Groovy 代碼,Jenkins pipeline 其實就是基于Groovy語言實作的一種DSL。 了解一些Groovy文法知識是很有必要的
不想本地安裝Groovy環境的話,可以打開 groovy-playground 運作線上groovy代碼,檢視結果 該網站可能需要會通路外國網站。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICMyYTMvw1dvwlMvwlM3VWaWV2Zh1Wa-cmbw5CZztWMjZXcoRzavwlNwMjMxQTMtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
image.png
必要的Groovy文法知識
- 定義變量和方法用def關鍵字,
def name="jack"
- 語句最後的分号不是必需的
- 方法調用時可以省略括号
def say(String name = "world") {
return "hi " + name
}
// 調用
say name = "jack"
複制
- 雙引号支援插值,單引号不會解析變量,原樣輸出
def name = 'world'
// 結果: hello world
print "hello ${name}"
// 結果: hello ${name}
print 'hello ${name}'
複制
- 三雙引号和三單引号都支援換行,隻有三雙引号支援插值
def foo = """ line one
line two
${name}
"""
複制
- 支援閉包
// 定義閉包
def codeBlack = {print "hello closure"}
// 閉包當做函數調用
codeBlack
// 閉包可以指派給變量,或者作為參數傳遞
def pipeline(closure) {
closure()
}
pipeline(codeBlack)
複制
// 因為括号是非必需的,下面幾種寫法結果是一樣的,是不是和Jenkins pipeline很像呢
pipeline( {print "hello closure"} )
pipeline {
print "hello closure"
}
pipeline codeBlack
複制
- 閉包的另一個用法
def stage(String name, closure) {
println name
closure()
}
// 正在情況下,我們這樣使用stage函數
stage("stage name", {
println "closure"
})
// 最終列印
/*
stage name
closure
*/
// 但是,在Groovy裡,可以直接這麼寫
stage("stage name") {
print "closure"
}
複制