name: gitlab-ci最佳实践 user-invocable: false description: 用于优化GitLab CI/CD管道以获取性能、可靠性或可维护性时。覆盖管道优化和组织模式。 allowed-tools:
- Read
- Write
- Edit
- Bash
- Grep
- Glob
GitLab CI - 最佳实践
优化GitLab CI/CD管道以获取性能、可靠性和可维护性。
流水线优化
使用依赖关系图与需求
stages:
- build
- test
- deploy
build:frontend:
stage: build
script: npm run build:frontend
build:backend:
stage: build
script: npm run build:backend
test:frontend:
stage: test
needs: ["build:frontend"]
script: npm run test:frontend
test:backend:
stage: test
needs: ["build:backend"]
script: npm run test:backend
deploy:
stage: deploy
needs: ["test:frontend", "test:backend"]
script: ./deploy.sh
并行执行
test:
parallel:
matrix:
- SUITE: [unit, integration, e2e]
script:
- npm run test:$SUITE
可中断作业
test:
interruptible: true
script:
- npm test
deploy:production:
interruptible: false # 永不取消
script:
- ./deploy.sh
配置组织
分割配置文件
# .gitlab-ci.yml
include:
- local: .gitlab/ci/build.yml
- local: .gitlab/ci/test.yml
- local: .gitlab/ci/deploy.yml
stages:
- build
- test
- deploy
可重用模板
.node_template: &node_template
image: node:20-alpine
before_script:
- npm ci
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
test:unit:
<<: *node_template
script:
- npm run test:unit
test:lint:
<<: *node_template
script:
- npm run lint
扩展关键字
.base_job:
image: node:20-alpine
before_script:
- npm ci
test:
extends: .base_job
script:
- npm test
build:
extends: .base_job
script:
- npm run build
资源管理
资源组
deploy:staging:
resource_group: staging
script:
- ./deploy.sh staging
deploy:production:
resource_group: production
script:
- ./deploy.sh production
运行器标签
heavy_build:
tags:
- high-memory
- docker
script:
- ./build.sh
错误处理
重试配置
test:flaky:
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
- script_failure
允许失败
test:experimental:
allow_failure: true
script:
- npm run test:experimental
test:experimental:soft:
allow_failure:
exit_codes: [42] # 仅允许特定退出码
安全最佳实践
受保护流水线
deploy:production:
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
environment:
name: production
安全变量
# 使用受保护和掩码的变量
deploy:
script:
- echo "$API_KEY" # 日志中掩码
rules:
- if: $CI_COMMIT_REF_PROTECTED == "true"
监控与调试
作业日志
test:
script:
- set -x # 启用调试输出
- npm test
after_script:
- echo "作业状态: $CI_JOB_STATUS"
流水线徽章
[](https://gitlab.com/group/project/-/pipelines)
[](https://gitlab.com/group/project/-/pipelines)
常见反模式
-
避免: 顺序运行所有作业 建议: 使用
needs实现并行执行 -
避免: 下载所有制品 建议: 使用
dependencies限制下载 -
避免: 每个作业都重建 node_modules 建议: 使用缓存和锁定文件键
-
避免: 硬编码秘密 建议: 使用受保护的CI/CD变量
-
避免: 单一庞大的
.gitlab-ci.yml文件 建议: 分割成多个包含文件