Jenkins CI/CD #1: Declarative 與 Scripted pipeline

Simon Chu
Bucketing
Published in
6 min readJul 22, 2020

讓我們由淺入深學習 Jenkins CI/CD

Photo by Charismareephotography on pngitem

首先介紹 Jenkins pipeline

Jenkins 為了要解決日漸龐大複雜的 Build Flow,2016 年四月 Jenkins 釋出了 Pipeline plugin,提供所謂的流水線建置功能來讓建置工作變得容易 Scale up。 而這個 Pipeline Plugin 是基於一種語言 Groovy。

為何 Jenkins pipeline 使用 Groovy 設計呢?主要是因為整個 Jenkins 都是使用 Java 開發而成,而 Java 卻不適合拿來設計 Build Job 的 DSL (Domain Specific Language),Groovy 既相容 Java, JVM 就被 Jenkins 拿來設計 Pipeline Plugin 了。

然而 Jenkins Pipeline 的語法分為兩種,Declarative Pipeline 與 Scripted Pipeline。

Declarative Pipeline

此種模式限制使用者使用嚴格與規範的架構,此方式使 pipline 相對簡易與相對容維護,因為 code style 皆會依照規範,且使用預設的句法。

  • 最上層 (最外層) 必須是一個 " block ",尤其是 : pipeline { }。
  • 沒有分號作為語句分隔符,且各行為一個指令。
  • Block 只能由節段 ( Sections )、指令 ( Directives )、步驟 ( Steps ) 或指定敘述 ( assignment statements ) 組成。
  • 屬性引用語句視為非參數方法引用。例如 : input 被視為 input()。

可使用之指令相關介紹 [官網連結]

舉例:

//Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
echo 'Hello world!'
}
}
}
}

Scripted Pipeline

此方式使 pipline 相對自由,只限制結構與語法須為 Groovy 所定義的,也因此 Scripted Pipeline 可以做到相對複雜的需求。

舉例:

//Jenkinsfile (Scripted Pipeline)
node {
stage('Stage 1') {
echo 'Hello world!'
}
}

若要使用 for 迴圈於 Declarative Pipeline 則需要使用 script block

//Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
script {
def browsers = ['chrome', 'firefox']
for (int i = 0; i < browsers.size(); i++) {
echo "Testing the ${browsers[i]} browser"
}
}
}
}
}
}

若在 Scripted Pipeline 則如下

//Jenkinsfile (Scripted Pipeline)
node {
stage('Example') {
echo 'Hello World'
browsers = ['chrome', 'firefox']
for (i in browsers) {
echo "Testing the ${i} browser"
}
}
}

結果如下:

在舉一個結合 Git 的範例 :
(Unit Test 需為開發者自行撰寫)

//Jenkinsfile (Declarative Pipeline)
pipeline {
agent any
stages {
stage('Git clone') {
steps {
git url: 'https://github.com/xchux/hello_world.git'
}
}
stage('Build') {
steps {
sh 'mvn package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
}
}

以下為 Scripted Pipeline

// Jenkinsfile (Scripted Pipeline)
node {
stage('git clone') {
git "https://github.com/xchux/hello_world.git"
}
stage('Build') {
echo 'Building....'
sh 'mvn package'
}
stage('Test') {
echo 'Testing....'
sh 'mvn test'
}
}

結果顯示如下:

看了這些範例是否對pipline有些觀念了呢?
但若每次有程式碼修改就需要到 Jenkins 寫或執行一個對應的 pipeline,那就太麻煩了
因此下一篇將介紹 :
如何連接 github 達到 CI ( Continuous Integration )

參考:

--

--