名称: gitlab-ci-管道配置 用户可调用: false 描述: 当配置GitLab CI/CD管道、定义阶段或设置工作流规则时使用。涵盖管道结构、阶段排序和执行流程。 允许工具:
- Read
- Write
- Edit
- Bash
- Grep
- Glob
GitLab CI - 管道配置
配置GitLab CI/CD管道,具有正确的阶段排序、工作流规则和执行流程。
管道结构
# .gitlab-ci.yml
stages:
- build
- test
- deploy
default:
image: node:20-alpine
before_script:
- npm ci --cache .npm --prefer-offline
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- .npm/
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
阶段配置
顺序阶段
stages:
- install
- lint
- test
- build
- deploy
阶段内的并行作业
test:unit:
stage: test
script: npm run test:unit
test:integration:
stage: test
script: npm run test:integration
test:e2e:
stage: test
script: npm run test:e2e
工作流规则
基于分支的管道
workflow:
rules:
- if: $CI_COMMIT_BRANCH == "main"
variables:
DEPLOY_ENV: production
- if: $CI_COMMIT_BRANCH =~ /^release\//
variables:
DEPLOY_ENV: staging
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
自动取消冗余管道
workflow:
auto_cancel:
on_new_commit: interruptible
使用Needs for DAG管道
build:
stage: build
script: npm run build
test:unit:
stage: test
needs: ["build"]
script: npm run test:unit
test:lint:
stage: test
needs: [] # 无依赖,立即运行
script: npm run lint
deploy:
stage: deploy
needs: ["build", "test:unit"]
script: npm run deploy
包含外部配置
include:
- local: .gitlab/ci/build.yml
- local: .gitlab/ci/test.yml
- project: 'my-group/my-templates'
ref: main
file: '/templates/deploy.yml'
- template: Security/SAST.gitlab-ci.yml
最佳实践
- 定义清晰的阶段排序
- 使用
needs优化管道执行 - 配置工作流规则以防止不必要的管道
- 使用
include拆分大型配置 - 为可取消作业设置适当的
interruptible标志