名称: gitlab-ci-构建物-缓存 用户可调用: 否 描述: 用于配置构建物以在作业间传递数据或缓存以加快构建。涵盖缓存策略和构建物管理。 允许工具:
- Read
- Write
- Edit
- Bash
- Grep
- Glob
GitLab CI - 构建物与缓存
配置构建物和缓存以实现高效的流水线执行。
构建物
基本构建物配置
build:
script:
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 week
构建物报告
test:
script:
- npm test -- --coverage
artifacts:
reports:
junit: junit.xml
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
条件性构建物
build:
artifacts:
paths:
- dist/
when: on_success # on_success, on_failure, always
exclude:
- dist/**/*.map
构建物依赖
build:
artifacts:
paths:
- dist/
test:
dependencies:
- build # 下载构建物
script:
- npm test
deploy:
dependencies: [] # 跳过所有构建物下载
script:
- ./deploy.sh
缓存
基本缓存配置
default:
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .npm/
缓存键策略
# 按分支缓存
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
# 基于锁定文件的缓存
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
# 组合键
cache:
key:
prefix: ${CI_JOB_NAME}
files:
- package-lock.json
paths:
- node_modules/
缓存策略
install:
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
policy: push # 仅上传缓存
script:
- npm ci
test:
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
policy: pull # 仅下载缓存
script:
- npm test
后备键
cache:
key: ${CI_COMMIT_REF_SLUG}
fallback_keys:
- ${CI_DEFAULT_BRANCH}
- main
paths:
- node_modules/
分布式缓存 (S3)
在 GitLab Runner 中配置:
[runners.cache]
Type = "s3"
Shared = true
[runners.cache.s3]
ServerAddress = "s3.amazonaws.com"
BucketName = "gitlab-runner-cache"
BucketLocation = "us-east-1"
构建物 vs 缓存
| 特征 | 构建物 | 缓存 |
|---|---|---|
| 目的 | 在作业间传递数据 | 加速作业执行 |
| 存储 | GitLab 服务器 | Runner 本地或 S3 |
| 可靠性 | 保证 | 尽力而为 |
| 过期时间 | 可配置 | 可配置 |
| 跨流水线 | 是(带依赖) | 是(带键) |
最佳实践
- 使用缓存处理依赖(如 node_modules, vendor)
- 使用构建物处理构建输出
- 设置适当的过期时间
- 使用基于锁定文件的缓存键
- 排除源映射和不必要文件
- 对仅读取缓存的作业使用
policy: pull