
在讓 Jenkins 串連 Github 之前,必須要先有一個 Public IP 的 Jenkins server,最方便的做法就是在雲端服務平台的 Linux VM 架設 Jenkins。可以參考我這篇在 Azure Linux VM 的作法。
首先我們先來設定 Github 的 Webhooks。先到 Github 上要串接的 repository 底下選擇「Settings」,再點選左列的「Webhooks」。進入 Webhooks設定後,按下 Add webhook 按鈕。

在 Payload URL 欄位填入 Jenkins server 的 URL 後面加上「github-webhook」,然後在 Content type 選擇 application/json,設定好之後按下 Add webhook 按鈕。

如果看到設定的 URL 前面出現綠勾勾就代表成功了。

接下來回到 Jenkins,先「新增作業」。

填寫 job 名稱,並且選擇 Pipeline。

在設定頁面的 Build Triggers 這邊把 GitHub hook trigger for GITScm polling 打勾。

在 Pipeline 的 definition 選擇 Pipeline script from SCM

其他的設定可以參考下圖,記得 Branch 的部分要注意,因為 Github 預設branch 名稱已經改成 main。Script path 指的是 Jenkinsfile 在 git repository 的路徑。

Jenkinsfile 的內容可以先複製下方內容,Jenkinsfile 的寫法可以參考這篇
pipeline {
agent any
stages {
stage('Static Analysis') {
steps {
echo 'Run the static analysis to the code'
}
}
stage('Compile') {
steps {
echo 'Compile the source code'
}
}
stage('Security Check') {
steps {
echo 'Run the security check against the application'
}
}
stage('Run Unit Tests') {
steps {
echo 'Run unit tests from the source code'
}
}
stage('Run Integration Tests') {
steps {
echo 'Run only crucial integration tests from the source code'
}
}
stage('Publish Artifacts') {
steps {
echo 'Save the assemblies generated from the compilation'
}
}
}
}
都設定好之後,按下「儲存」按鈕就完成了。接下來到剛剛建好的 job 並且按下「馬上建置」。

都沒問題的話,應該會看到下圖的結果。

這時候回到 GitHub,在串接好的 repository 做 git push,就會發現 Jenkins的 job 已自動被 trigger了。