1. 程式人生 > >CI/CD之Gitlab整合Jenkins多分支pipeline實現質量檢測和自動釋出

CI/CD之Gitlab整合Jenkins多分支pipeline實現質量檢測和自動釋出

本次實施主要實現:

  • 程式碼提交gitlab,自動觸發Jenkins構建
  • gitlab發起Merge Request, 需要Jenkins檢查通過才可以merge,實現程式碼review和質量管控
  • gitlab開發分支merge後自動釋出到test環境
  • gitlab master分支merge後自動釋出到prod環境

Jenkins Config

  • 安裝外掛Gitlab, 使用教程: https://github.com/jenkinsci/gitlab-plugin#pipeline-jobs
  • 安裝外掛Pipeline Utility Steps, 用來讀取檔案
  • 安裝外掛Warnings Next Generation , 使用教程:https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md#quality-gate-configuration

配置gitlab connection

系統設定-gitlab

配置API token, 需要登陸gitlab,給一個developer角色的賬號,在系統設定中找到access token, 獲取token。 然後在Jenkins中配置Gitlab API Toekn的憑證。

Jenkins多分支Job

新建多分支流水線任務。

配置分支源,輸入gitlab地址,建立一個username password token, 填入gitlab的賬號和密碼。其他預設讀取根目錄下的jenkinsfile檔案。
https://github.com/Ryan-Miao/code-quality-verify-demo/blob/master/Jenkinsfile

接下來重點就是Jenkinsfile裡的配置。

主要有:

獲取gitlab connection, 填寫我們之前配置gitlab connection

properties([gitLabConnection('gitlab-bigdata')])

拉取程式碼

checkout scm

告訴gitlab job狀態

updateGitlabCommitStatus name: 'build', state: 'pending'

不同分支走不同的構建方式

if (env.BRANCH_NAME == 'master' || env.BRANCH_NAME == 'dev' ) {
        stage("Build Docker Image"){
            echo "build docker image"
            echo "Only dev/master branch can build docker image"
        }

        if(env.BRANCH_NAME == 'dev'){
            stage("Deploy to test"){
                echo "branch dev to deploy to environment test"
            }

            stage("Integration test"){
                echo "test環境整合測試"
            }

        }

        if(env.BRANCH_NAME == 'master'){
            stage("Deploy to prod"){
                echo "branch master to deploy to environment prod"
            }

            stage("Health check"){
                echo "prod檢查"
            }

        }
    }

點選立即構建即可。

觸發方式可以選擇手動觸發,定時觸發(比如每分鐘), gitlab trigger.

Gitlab Merge Request

gitlab在專案設定中,找到Merge Request

Only allow merge requests to be merged if the pipeline succeeds 
Pipelines need to be configured to enable this feature. 
Only allow merge requests to be merged if all discussions are resolved

當我們發起一個M-R

當pipeline構建成功之後:

我們Jenkinsfile裡設定不同分支的構建策略,這樣就實現了不同環境的釋出和質量校驗。需要注意的是,當代碼合併到master的時候,我們的功能就會執行釋出策略了。而實際上,我們應該釋出到canary金絲雀環境,即預生產環境,等確保沒有任何問題之後再手動釋出到prod。這裡簡化處理髮布流程,直接釋出。

參考

  • https://jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline