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。这里简化处理发布流程,直接发布。

参考

posted @ 2019-06-17 15:35  Ryan.Miao  阅读(8525)  评论(2编辑  收藏  举报