經過前幾天的基礎建置,我們已經準備好了所有零件:SonarQube 伺服器、Jenkins Agent、Shared Library 以及 Vault 秘密管理。今天,我們將把這些零件聯動起來,構建一條專業級的程式碼品質掃描 Workflow。
在 CI/CD 流程中,掃描只是手段,Quality Gate 才是目的。它是一組自動化的評估準則,決定了目前的程式碼是否「足夠好」以進入下一階段。如果程式碼不符合指標(例如:出現了新的嚴重漏洞、單元測試覆蓋率未達標),Quality Gate 會將狀態標記為 Failed。
這是本篇最關鍵的技術點。在 Pipeline 中,當我們上傳分析報告後,Jenkins 不會立即知道結果。
SonarScanner 將數據上傳至 SonarQube。waitForQualityGate() 捕捉到這個 Webhook 後,才會結束「暫停」狀態,並返回結果。注意:如果未在 SonarQube 中配置對應 Jenkins 的 Webhook 地址,
waitForQualityGate會一直等待直到超時。
@Library('common-pipeline-library') _
pipeline {
agent { label 'dotnet' }
stages {
stage('SonarQube Build & Scan') {
steps {
script {
// 使用 Shared Library 封裝的工具路徑
def sqScanner = tool 'SonarQube MSBuild Scanner'
// withSonarQubeEnv 會自動注入 URL 與 Credentials
withSonarQubeEnv('SonarQube') {
// 開始分析 (參數 /k 代表 Project Key, /n 代表 Project Name)
sh "${sqScanner}/SonarScanner.MSBuild.exe begin /k:\"my-project\" /n:\"my-project\""
sh "dotnet build my-project.sln --configuration Release"
sh "${sqScanner}/SonarScanner.MSBuild.exe end"
}
}
}
}
stage('Quality Gate Check') {
steps {
script {
// 設定超時防止 Pipeline 永久掛起
timeout(time: 5, unit: 'MINUTES') {
// 等待 Webhook 回傳結果
def qg = waitForQualityGate()
if (qg.status != 'OK') {
// 主動拋出錯誤,強制中斷 Pipeline
error "Pipeline aborted due to Quality Gate failure: ${qg.status}"
}
}
}
}
}
}
}
在 SonarQube UI 中,我們建議為「New Code (新程式碼)」設定以下門檻:
0 (零容忍)。0 (安全性優先)。80% (確保測試跟上進度)。3% (防止 Copy-Paste 濫用)。透過聯動 Webhook 與 waitForQualityGate,我們建立了一個「無人值守」的品質檢查站。這確保了只有健康的程式碼能夠進入 CD(持續部署)階段。
至此,CI(持續整合)的部分已經告一段落。從明天開始,我們將正式跨入 CD 的領域,探討如何安全地將這些通過檢核的產出物,部署到多樣化的運行環境中。