.gitlab.yml通过仓库统一配置

1. 遇到的问题

在我们的微前端开发中,子服务的 cicd 基本是一样的,如果需要改动其中的某一步,就会涉及把所有子服务中的 .gitlab.yml 文件都改一遍,这样就会发现很繁琐,所以有没有办法统一做配置的吗?

2. 示例

原本子服务中 .gitlab.yml 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
variables:
GIT_SUBMODULE_STRATEGY: recursive

before_script:
- git config --global user.name "${GITLAB_USER_NAME}"
- git config --global user.email "${GITLAB_USER_EMAIL}"

stages:
- build
build:
stage: build
image: hub.docker.com/ci/ci-nodejs:14.5.0
script:
- npm install
- npm run build
- npm run cdn
only:
- /^v?\d+(\.\d+)+[\.\-_\w]*/
tags:
- i7

目前build阶段有 3 步骤,如果我们需要加一个发现通知 npm run notification

解决方法

  1. 在每个子服务中都添加该步骤-缺点比较麻烦,还有如果下次再改,还有重复修改;
  2. 通过仓库配置,统一管理 .gitlab.yml 的配置-优点只需要配置一次,后面都只要改仓库中模板的配置就行

3. 配置

1. 创建一个配置的仓库和文件

配置仓库比如: ci_template,在仓库中新建模板文件如: web-childServise-ci-base.yml 文件内容基本和子服务的一致

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# web-childServise-ci-base.yml
variables:
GIT_SUBMODULE_STRATEGY: recursive

before_script:
- git config --global user.name "${GITLAB_USER_NAME}"
- git config --global user.email "${GITLAB_USER_EMAIL}"

stages:
- build
build:
stage: build
image: hub.docker.com/ci/ci-nodejs:14.5.0
script:
- npm install
- npm run build
- npm run cdn
- npm run notification # 新加的通知
only:
- /^v?\d+(\.\d+)+[\.\-_\w]*/
tags:
- i7

2. 修改子服务中 .gitlab.yml 文件

1
2
3
4
5
6
7
8
9
10
11
# .gitlab.yml
variables:
GIT_SUBMODULE_STRATEGY: recursive

include:
# base 仓库的路径
- project: 'devops/ci_template'
file: '/web/web-childServise-ci-base.yml'
# ref 可以不配置,默认是 master 分支
ref: 'feature/addNotification'
# 指定仓库的具体分支,一般测试 ci 脚本时候用

4. 总结

通过仓库统一配置,这样如果下次需要更改 runner 机器或者添加新脚本,通过直接修改统一的配置,在子服务触发新的构建的时候就会使用最新的配置去跑服务