Gitlab CI/CD
Gitlab自带CI/CD功能,想要使用只需要
1.在相应的Repository中添加.gitlab-ci.yml文件,
2.配置Gitlab Runner
Baisc
Pipeline
一次Commit或者Merge Request可以触发一次Pipeline,在这个Pipeline中完成CI所需要的全部流程,如安装依赖、运行测试、编译、部署测试服务器、部署生产服务器等
而具体的触发条件和需要执行的流程都在.gitlab-ci.yml文件中配置
+------------------+ +----------------+
| | trigger | |
| Commit / MR +---------->+ Pipeline |
| | | |
+------------------+ +----------------+
Stages
一次Pipeline由一个或多个Stage组成,表示CI的不同阶段,如build, test, deploy
- 所有
Stages会按照顺序运行,即当一个Stage完成后,下一个Stage才会开始 - 只有当所有
Stages完成后,该Pipeline才会成功 - 如果任何一个
Stage失败,那么后面的Stages不会执行,该Pipeline失败
+--------------------------------------------------------+
| |
| Pipeline |
| |
| +-----------+ +------------+ +------------+ |
| | Stage 1 |---->| Stage 2 |----->| Stage 3 | |
| +-----------+ +------------+ +------------+ |
| |
+--------------------------------------------------------+
Jobs
一个Stage有一个或多个Jobs组成,定义真正需要执行的脚本命令
- 相同
Stage中的Jobs会并行执行 - 相同
Stage中的Jobs都执行成功时,该Stage才会成功 - 如果任何一个 Job 失败,那么该
Stage失败 - 所有
Job默认都是从clean workspace开始执行的,即在执行前会删除其它Job的执行产物
+------------------------------------------+
| |
| Stage 1 |
| |
| +---------+ +---------+ +---------+ |
| | Job 1 | | Job 2 | | Job 3 | |
| +---------+ +---------+ +---------+ |
| |
+------------------------------------------+
.gitlab-ci.yml
basic
stages:
- build
- test
job1:
stage: test
script:
- echo "I am job1"
- echo "I am in test stage"
job2:
stage: build
script:
- echo "I am job2"
- echo "I am in build stage"
其中stages定义了build与test这两个stage的执行顺序
job1, job2分别定义了其所属的stage及所需要执行的具体命令
缓存
默认情况下每个Job都是从零开始执行,无法使用前一个Job的执行产物,需要特别指定
cache
cache字段可以指定在Job执行过程中需要保存并再次使用的文件。Gitlab的页面上有“清空所有缓存”功能的按钮
cache:
paths:
- path1
- path2
artifacts
artifacts字段同样可以指定在Job执行过程中需要保存并再次使用的文件。Gitlab会自动将artifacts保存的文件打包并提供下载连接
artifacts:
paths:
- ./build/output
虽然两者都可以缓存文件,但从Gitlab对待两者的方式可以看出,cache通常用来缓存中间产出和依赖项,而artifacts用来缓存最终产物
Gitlab Runner
所有的Pipeline都需要在Gitlab Runner中执行,Gitlab中并不包含Gitlab Runner需要另外安装。
之所以分开是由于执行Pipeline通常很消耗系统资源,为了减少对Gitlab Server性能的影响,可以将其安装在其它一台或多台机器上
Install
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
export GITLAB_RUNNER_DISABLE_SKEL=true; sudo -E apt-get install gitlab-runner
Register
有三种不同类型的Runner:
- Shared (for all projects): Admin Area Overview > Runners
- Group (for all projects in a group): Repository Setting > CI/CD and expand the Runners secction
- Specific (for specific projects): Repository Setting > CI/CD and expand the Runners section
# 根据Runner的类型在各自的配置页面查找对应的注册信息
sudo gitlab-runner register
Trivia
Shallow cloning
只需要添加变量GIT_DEPTH即可
variables:
GIT_DEPTH: 5
也可以在页面Setting > CI/CD > Variables中添加
