本次实施主要实现:html
- 代码提交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 connectiongit
系统设置-gitlab github
配置API token, 须要登录gitlab,给一个developer角色的帐号,在系统设置中找到access token, 获取token。 而后在Jenkins中配置Gitlab API Toekn的凭证。web
Jenkins多分支Job
新建多分支流水线任务。docker
配置分支源,输入gitlab地址,建立一个username password token, 填入gitlab的帐号和密码。其余默认读取根目录下的jenkinsfile文件。 https://github.com/Ryan-Miao/code-quality-verify-demo/blob/master/Jenkinsfileide
接下来重点就是Jenkinsfile里的配置。gitlab
主要有:测试
获取gitlab connection, 填写咱们以前配置gitlab connectionui
properties([gitLabConnection('gitlab-bigdata')])
拉取代码this
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。这里简化处理发布流程,直接发布。
参考
原文出处:https://www.cnblogs.com/woshimrf/p/gitlab-with-jenkins.html