CI/CD之Gitlab集成Jenkins多分支pipeline實現質量檢測和自動發布


本次實施主要實現:

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

Jenkins Config

配置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 trigger jenkins

對於多分支jenkins任務,trigger配置很簡單。直接在gitlab項目配置中,找到integration,直接配置jenkins項目地址即可,選中push events和merge request events.

http://JENKINS_URL/project/PROJECT_NAME

When you configure the plugin to trigger your Jenkins job, by following the instructions below depending on job type, it will listen on a dedicated URL for JSON POSTs from GitLab's webhooks. That URL always takes the form http://JENKINS_URL/project/PROJECT_NAME, or http://JENKINS_URL/project/FOLDER/PROJECT_NAME if the project is inside a folder in Jenkins. You should not be using http://JENKINS_URL/job/PROJECT_NAME/build or http://JENKINS_URL/job/gitlab-plugin/buildWithParameters, as this will bypass the plugin completely.

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。這里簡化處理發布流程,直接發布。

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM