一、需求背景
随着前端开发工程化的发展, 为了提高项目的开发效率
、代码可维护性
、代码质量
、代码规范
、业务正确性
、以及项目的可持续发布
。项目通常需要有:
- 代码规范验
- 单元测试
- 代码编译
- 版本日志
- 版本release
这些工作是重复的,其中代码规范
,单元测试
,是开发人员需要遵守做好的。为了保证主分支代码的正确性,我们需要一个统一的地方来集成这些功能,在代码push或者merge之前验证。代码通过了才能merge或者release. 由此想到用jenkins才集成这些功能,通过gitlab webhooks实现自动化持续集成,
二、工作流程
work flow
三、环境
linux
服务器一台并安装好jenkins
、nodejs
、gitlab
。 gitlab可以使用官方在线版本
上述软件安装教程官方已经说的很清楚,这里不做多的描述。
- jenkins: https://jenkins.io/download/
- nodejs: http://nodejs.cn/download/
- gitlab: https://about.gitlab.com/
四、配置
jenkins
1. 安装对应的插件
在jenkins安装的时候可以选择 install suggested plugins 这样 大部分常用的插件就会自动装上,后续一些我们需要的可以在单独安装。大概需要pipeline, git, gitlab相关的插件
image.png
2. New Item
image.png
image.png
3.配置Item
a. 基本的一些选项
image.png
b. pipeline的基本配置
Pipeline 有两种模式:(1).
pipeline script
: 直接jenkins服务端填写脚本image.png
(2).
pipeline srcipt form SCM
: 这是我们要使用的方式, 如图显示,这里我们需要填code git repository地址
、ssh 私钥
、branches to build
、pipeline执行的脚本文件路径
image.png
如果没有配置linux服务端 jenkins ssh私匙和gitlab公钥。会提示错误如图错误:
image.png
- error msg
Failed to connect to repository : Command "git -c core.askpass=true ls-remote -h git@XXXXX:XXXX/XXXX.git HEAD" returned status code 128:
stdout:stderr: Permission denied, please try again.Permission denied, please try again.Permission denied (publickey,password).fatal: Could not read from remote repository.Please make sure you have the correct access rightsand the repository exists.
4.为jenkins添加私钥
image.png
image.png
image.png
5.配置jenkins gitlab web hook 信息
image.png
image.png
image.png
image.png
6.gitlab 生产 user token
image.png
7.gitlab webhook 配置
image.png
测试连接是否成功
连接成功
8.项目代码配置Jenkinsfile
sourceBranch = env.gitlabBranch ?: env.gitlabSourceBranch
currentBuild.displayName = sourceBranch
node {
env.PATH="/usr/local/node-v6.11.4-linux-x64/bin:${env.PATH}"
gitlabCommitStatus {
stage ('Checkout') {
checkout scm
}
stage ('install') {
sh 'npm install --no-spin'
}
stage ('test') {
sh "npm run test"
}
}
}
说明:在jenkins普通任务,有
Publish build status to Gitlab
,但是pipeline里面没有这个选项,我们通过 Jenkinsfile里面的gitlabCommitStatus实现
9. push code 实现效果
image.png
image.png