深色模式
GitLab CI 入门:写 .gitlab-ci.yml
摘要:GitLab CI 的全部配置就是仓库根目录的
.gitlab-ci.yml。本文从最小可用配置开始,逐步加上缓存、制品、变量和手动发布门禁,最后给出调试技巧。
适用环境
- 一个 GitLab 仓库(gitlab.com 或自建实例均可)
- 项目已注册可用的 GitLab Runner
- 项目有可执行的构建/测试命令
操作步骤
1. 最小可用配置
bash
cat > .gitlab-ci.yml <<'EOF'
stages:
- build
build:
stage: build
script:
- echo "building..."
EOF
git add .gitlab-ci.yml && git commit -m "add ci" && git push1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
推送后到仓库左侧 Build → Pipelines 查看运行状态。
2. 补全 stages、缓存与制品
yaml
stages: [lint, test, build, deploy]
build:
stage: build
script:
- mkdir -p dist && echo "artifact" > dist/app.txt
artifacts:
paths: [dist/]
expire_in: 1 week
cache:
key:
files: [pom.xml]
paths: [.m2/repository] # 缓存不保证命中,可靠传递必须用 artifacts1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
3. rules 控制执行时机
yaml
test:
stage: test
script: ["make test"]
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'1
2
3
4
5
6
2
3
4
5
6
4. 变量、Secret 与手动门禁
yaml
deploy_prod:
stage: deploy
variables:
DEPLOY_ENV: production
script: ["./deploy.sh prod"]
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
when: manual # 需要人工点播放按钮
environment:
name: production1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
敏感值在 Settings → CI/CD → Variables 添加,勾选 Masked(日志打码)和 Protected(仅受保护分支可见)。
危险
不要把生产 Token 放在未勾选 Protected 的变量里。任何能开分支的人都能读到非 Protected 变量,等于密钥公开。
验证
仓库页面 Build → Pipeline editor → Validate 可在线校验语法。
- [ ] Pipelines 页面出现新流水线且按 stage 顺序执行
- [ ] build job 的 artifacts 可以在页面下载
- [ ]
deploy_prod显示为「手动」按钮,不点就不执行 - [ ] 故意写错缩进,Validate 会报错
常见坑
YAML 缩进错误
script 列表、rules 的 if 都必须对齐。用 Pipeline editor 的 Validate 或 yamllint 先检查。
cache 与 artifacts 用反
cache 不保证传递,artifacts 才保证。跨 job 传二进制必须用 artifacts。
Runner 标签不匹配
自建 Runner 设了 tag 而 job 没匹配,流水线会一直 pending。