GitLabCI/CD管道配置Skill gitlab-ci-pipeline-configuration

该技能用于配置和管理GitLab持续集成/持续部署(CI/CD)管道,实现自动化软件构建、测试和部署流程。包括定义阶段顺序、设置工作流规则、优化执行依赖和集成外部配置,适用于DevOps实践,提升开发效率和交付质量。关键词:GitLab CI/CD, 管道配置, DevOps, 自动化部署, 阶段管理, 工作流规则, 持续集成, 持续部署, 软件交付。

CI/CD 0 次安装 0 次浏览 更新于 3/25/2026

名称: 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

最佳实践

  1. 定义清晰的阶段排序
  2. 使用 needs 优化管道执行
  3. 配置工作流规则以防止不必要的管道
  4. 使用 include 拆分大型配置
  5. 为可取消作业设置适当的 interruptible 标志