在 GitLab CI 中配置多任务

发布于:2025-06-26 ⋅ 阅读:(13) ⋅ 点赞:(0)

GitLab CI 通过 .gitlab-ci.yml 文件定义流水线,多任务可以通过 stagesjobs 实现。每个任务(Job)可以独立运行或依赖其他任务。

定义多个阶段(Stages)

阶段是任务的逻辑分组,任务按阶段顺序执行。默认包含 buildtestdeploy 三个阶段,但可以自定义。

stages:
  - build
  - test
  - deploy

配置多个任务(Jobs)

每个任务属于一个阶段,通过 stage 字段指定。以下示例定义了三个任务:

build_job:
  stage: build
  script:
    - echo "Running build tasks"
    - make build

test_job:
  stage: test
  script:
    - echo "Running tests"
    - make test

deploy_job:
  stage: deploy
  script:
    - echo "Deploying application"
    - make deploy

并行执行任务

同一阶段的任务会并行执行。例如,以下两个测试任务会在 test 阶段并行运行:

test_unit:
  stage: test
  script:
    - echo "Running unit tests"
    - npm test

test_integration:
  stage: test
  script:
    - echo "Running integration tests"
    - npm run test:integration

任务依赖与条件执行

通过 needs 字段定义任务依赖关系,跳过阶段限制:

deploy_job:
  stage: deploy
  needs: ["test_job"]
  script:
    - echo "Deploying only if test_job passes"

通过 rulesonly/except 控制任务触发条件:

deploy_prod:
  stage: deploy
  script:
    - echo "Deploy to production"
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

使用模板减少重复代码

通过 extends 或锚点(YAML 特性)复用配置:

.tests:
  script:
    - echo "Running common test steps"

test_unit:
  extends: .tests
  script:
    - echo "Running unit tests"

test_integration:
  extends: .tests
  script:
    - echo "Running integration tests"

多项目流水线(父子流水线)

通过 trigger 启动多项目协作:

stages:
  - deploy

deploy_job:
  stage: deploy
  trigger:
    project: my-group/deploy-tools
    strategy: depend

使用变量和缓存优化任务

共享变量和缓存提升效率:

variables:
  PROJECT_NAME: "my-app"

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/

build_job:
  stage: build
  script:
    - echo "Building ${PROJECT_NAME}"
    - npm install

通过以上方法可以灵活配置多任务流水线,适应复杂的工作流需求。


网站公告

今日签到

点亮在社区的每一天
去签到