关于 gitlab-ci-generator
用于生成 GitLab CI/CD 流水线配置的技能,涵盖基础构建、Docker、Kubernetes、多项目和可复用模板。它按复杂度选择流程,并要求校验完整流水线;工具或参考资料不可用时会说明备用处理。
主要功能
- 01按复杂度路由请求
- 02生成常见流水线类型
- 03支持可复用模板与编排
- 04遵循安全和 CI 规范
- 05校验完整流水线
适用场景
- 01创建基础 GitLab CI/CD 流水线
- 02构建并部署 Docker 镜像
- 03将应用部署到 Kubernetes
- 04协调多项目流水线
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ akin-ozer/ cc-devops-skills --skill gitlab-ci-generator安装后在 Claude Code 中输入/gitlab-ci-generator确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
.gitignoreassets/templates/basic-pipeline.ymldocker-build.ymlkubernetes-deploy.ymlmulti-project.ymlreferences/best-practices.mdcommon-patterns.mdgitlab-ci-reference.mdsecurity-guidelines.mdtests/test_skill_contract.py详细介绍
GitLab CI/CD 流水线生成器
概述
根据当前最佳实践、安全标准和命名约定,生成可用于生产环境的 GitLab CI/CD 流水线配置。所有生成的资源都会使用 devops-skills:gitlab-ci-validator 技能自动验证,以确保语法正确并符合最佳实践。
触发短语
用户提出以下 GitLab CI/CD 生成请求时,使用此技能:
- “为……创建
.gitlab-ci.yml” - “为 Node/Python/Java 构建 GitLab 流水线”
- “在 GitLab CI 中添加 Docker 构建和部署作业”
- “设置 GitLab 父子流水线或多项目流水线”
- “在 GitLab CI 中加入 SAST/依赖扫描模板”
执行模型
按顺序遵循此确定性流程:
- 对请求复杂度进行分类(
targeted、lightweight或full)。 - 仅加载该复杂度所需的参考层级。
- 针对所选模式,输出相应的响应配置。
- 生成完整流水线时,从最接近的模板开始并进行自定义。
- 使用严格的 Critical/High 门槛验证完整流水线。
- 提供输出,并注明验证状态及模板/版本信息。
如果无法使用工具,请采用文档说明的备用流程,并明确报告。
模式路由(快速决策)
| 请求类型 | 模式 | 必需的参考资料 | 输出配置 |
|---|---|---|---|
| 包含常见作业/阶段、风险较低的简单单文件流水线 | Lightweight | Tier 1(仅在需要时加 Tier 2) | Lightweight 确认 + 精简的最终章节 |
多环境部署、高级 rules、include/模板、安全/合规敏感工作流,或要求不明确/存在风险 | Full | Tier 1 + Tier 2(仅在需要时加 Tier 3) | Full 确认 + 完整的最终章节 |
| 审查/问答/代码片段/针对性修复(非生成完整文件) | Targeted | 仅直接相关的文件 | 简洁的针对性回复(不使用完整模板) |
对于完整生成请求,如果无法确定模式,则选择 Full 模式。
生成前必须执行的步骤
关键: 生成任何完整的 GitLab CI/CD 流水线之前,必须完成以下步骤。
步骤 1:对复杂度分类(必需)
| 模式 | 适用情况 | 最低确认要求 |
|---|---|---|
| Targeted | 用户要求审查/问答/代码片段/针对性修复,未要求生成完整流水线 | 简洁的针对性回复 |
| Lightweight | 简单的单文件流水线、常见阶段/作业、不使用高级 GitLab 功能、不涉及敏感的部署/安全自定义 | Lightweight 确认 |
| Full | 多环境部署、include/模板、高级 rules 逻辑、安全扫描自定义、合规敏感工作流,或任何不明确/存在风险的请求 | Full 确认 |
对于完整生成请求,如果无法确定模式,默认选择 Full 模式。
步骤 2:按层级加载参考资料(必需)
根据所选模式,使用打开/读取操作加载参考资料。
定向模式(审查/问答/代码片段/聚焦修复):
- 仅加载与限定请求直接相关的参考资料/模板。
- 不强制执行完整生成模式的 Tier 1/Tier 2 清单项。
Tier 1(轻量模式和完整模式下生成完整流水线时必需):
references/best-practices.md- 基础安全性、性能和命名规范references/common-patterns.md- 用于选择起始模式assets/templates/中匹配的模板:- Docker 流水线 →
assets/templates/docker-build.yml - Kubernetes 部署 →
assets/templates/kubernetes-deploy.yml - 多项目流水线 →
assets/templates/multi-project.yml - 基础流水线 →
assets/templates/basic-pipeline.yml
- Docker 流水线 →
Tier 2(完整模式下必需;轻量模式下可选):
references/gitlab-ci-reference.md- 关键字/语法的边缘情况references/security-guidelines.md- 安全敏感控制措施
Tier 3(有条件地查询外部文档):
- 仅在本地参考资料未涵盖所请求的功能或特定版本行为时使用。
- 遵循“处理 GitLab CI/CD 文档查询”中的查询流程。
如果所需的本地参考资料或模板不可用:
- 报告缺失文件的确切路径。
- 使用现有参考资料继续,并明确标注假设。
- 在解决关键输入缺失问题之前,不得声称已达到可用于生产环境的可信度。
步骤 3:确认理解(必须明确输出)
轻量确认模式
仅用于简单请求。
必需格式:
## Reference Analysis Complete (Lightweight)
**Pattern:** [Pattern name] from common-patterns.md
**Template:** [Template file]
**Key standards to enforce:**
- [2-3 concrete standards]
示例:
## Reference Analysis Complete (Lightweight)
**Pattern:** Basic Build-Test-Deploy from common-patterns.md
**Template:** assets/templates/basic-pipeline.yml
**Key standards to enforce:**
- Pin runtime image versions (no `:latest`)
- Add explicit job timeouts
- Use `rules` instead of deprecated `only`/`except`
完整确认模式
用于复杂或安全敏感请求。
必需格式:
## Reference Analysis Complete (Full)
**Pipeline Pattern Identified:** [Pattern name] from common-patterns.md
- [Brief description of why this pattern fits]
**Best Practices to Apply:**
- [List 3-5 key best practices relevant to this pipeline]
**Security Guidelines:**
- [List security measures to implement]
**Template Foundation:** [Template file name]
- [What will be customized from this template]
示例:
## Reference Analysis Complete (Full)
**Pipeline Pattern Identified:** Docker Build + Kubernetes Deployment from common-patterns.md
- User needs containerized deployment to K8s clusters with staging/production environments
**Best Practices to Apply:**
- Pin all Docker images to specific versions (not `:latest`)
- Use caching for pip dependencies
- Implement DAG optimization with `needs` keyword
- Set explicit timeout on all jobs (15-20 minutes)
- Use `resource_group` for deployment jobs
**Security Guidelines:**
- Use masked CI/CD variables for secrets (KUBE_CONTEXT, registry credentials)
- Include container scanning with Trivy
- Never expose secrets in logs
**Template Foundation:** assets/templates/docker-build.yml + assets/templates/kubernetes-deploy.yml
- Combine Docker build pattern with K8s kubectl deployment
- Add Python-specific test jobs
生成完整流水线时,不允许跳过确认。
核心能力
1. 生成基础 CI/CD 流水线
创建完整、可用于生产环境的 .gitlab-ci.yml 文件,采用规范的结构、安全最佳实践和高效的 CI/CD 模式。
适用场景:
- 用户请求:“为……创建 GitLab 流水线”“构建 CI/CD 流水线”“生成 GitLab CI 配置”
- 场景:CI/CD 流水线、自动化测试、构建自动化、部署流水线
流程:
- 了解用户的需求(需要自动化哪些内容)
- 确定阶段、作业、依赖项和制品
- 使用
assets/templates/basic-pipeline.yml作为结构基础 - 参考
references/best-practices.md中的实现模式 - 参考
references/common-patterns.md中的标准流水线模式 - 遵循以下原则生成流水线:
- 使用语义清晰的阶段和作业名称
- 将 Docker 镜像固定到特定版本(不要使用 :latest)
- 使用掩码变量妥善管理密钥
- 使用依赖项缓存来提升性能
- 设置合理的制品过期时间,妥善处理制品
- 适用时使用
needs关键字优化 DAG - 使用 retry 和 allow_failure 妥善处理错误
- 使用
rules,而不是已弃用的 only/except - 为所有作业设置明确的
timeout(通常为 10-30 分钟) - 在注释中添加有意义的作业说明
- 始终使用 devops-skills:gitlab-ci-validator 技能验证生成的流水线
- 如果验证失败,修复问题并重新验证
示例结构:
# Basic CI/CD Pipeline
# Builds, tests, and deploys the application
stages:
- build
- test
- deploy
# Global variables
variables:
NODE_VERSION: "20"
DOCKER_DRIVER: overlay2
# Default settings for all jobs
default:
image: node:20-alpine
timeout: 20 minutes # Default timeout for all jobs
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
before_script:
- echo "Starting job ${CI_JOB_NAME}"
tags:
- docker
interruptible: true
# Build stage - Compiles the application
build-application:
stage: build
timeout: 15 minutes
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
expire_in: 1 hour
rules:
- changes:
- src/**/*
- package*.json
when: always
- when: on_success
# Test stage
test-unit:
stage: test
needs: [build-application]
script:
- npm run test:unit
coverage: '/Coverage: \d+\.\d+%/'
artifacts:
reports:
junit: junit.xml
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
test-lint:
stage: test
needs: [] # Can run immediately
script:
- npm run lint
allow_failure: true
# Deploy stage
deploy-staging:
stage: deploy
needs: [build-application, test-unit]
script:
- npm run deploy:staging
environment:
name: staging
url: https://staging.example.com
rules:
- if: $CI_COMMIT_BRANCH == "develop"
when: manual
deploy-production:
stage: deploy
needs: [build-application, test-unit]
script:
- npm run deploy:production
environment:
name: production
url: https://example.com
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
resource_group: production
2. 生成 Docker 构建流水线
创建用于构建、测试 Docker 镜像并将其推送到容器注册表的流水线。
使用场景:
- 用户请求:“创建 Docker 构建流水线……”“构建并推送 Docker 镜像……”
- 场景:容器构建、多阶段 Docker 构建、推送到注册表
流程:
- 了解 Docker 构建需求(基础镜像、注册表、标签)
- 使用
assets/templates/docker-build.yml作为基础 - 使用 Docker-in-Docker 或 Kaniko 进行构建
- 配置注册表身份验证
- 实施镜像标记策略
- 根据需要添加安全扫描
- 始终使用 devops-skills:gitlab-ci-validator 技能进行验证
示例:
stages:
- build
- scan
- push
variables:
DOCKER_DRIVER: overlay2
IMAGE_NAME: $CI_REGISTRY_IMAGE
IMAGE_TAG: $CI_COMMIT_SHORT_SHA
# Build Docker image
docker-build:
stage: build
image: docker:24-dind
timeout: 20 minutes
services:
- docker:24-dind
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script:
- docker build
--cache-from $IMAGE_NAME:latest
--tag $IMAGE_NAME:$IMAGE_TAG
--tag $IMAGE_NAME:latest
.
- docker push $IMAGE_NAME:$IMAGE_TAG
- docker push $IMAGE_NAME:latest
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
retry:
max: 2
when:
- runner_system_failure
# Scan for vulnerabilities
container-scan:
stage: scan
image: aquasec/trivy:0.49.0
timeout: 15 minutes
script:
- trivy image --exit-code 0 --severity HIGH,CRITICAL $IMAGE_NAME:$IMAGE_TAG
needs: [docker-build]
allow_failure: true
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
3. 生成 Kubernetes 部署流水线
创建用于将应用部署到 Kubernetes 集群的流水线。
使用场景:
- 用户请求:“部署到 Kubernetes……”“创建 K8s 部署流水线……”
- 场景:Kubernetes 部署、Helm 部署、kubectl 操作
流程:
- 确定 Kubernetes 部署方式(kubectl、Helm、Kustomize)
- 使用
assets/templates/kubernetes-deploy.yml作为基础 - 配置集群身份验证(服务账户、kubeconfig)
- 实施适当的环境管理
- 添加回滚功能
- 始终使用 devops-skills:gitlab-ci-validator 技能进行验证
示例:
stages:
- build
- deploy
# Kubernetes deployment job
deploy-k8s:
stage: deploy
image: bitnami/kubectl:1.29
timeout: 10 minutes
before_script:
- kubectl config use-context $KUBE_CONTEXT
script:
- kubectl set image deployment/myapp myapp=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA -n $KUBE_NAMESPACE
- kubectl rollout status deployment/myapp -n $KUBE_NAMESPACE --timeout=5m
environment:
name: production
url: https://example.com
kubernetes:
namespace: production
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
resource_group: k8s-production
retry:
max: 2
when:
- runner_system_failure
4. 生成多项目流水线
创建可触发其他项目或采用父子流水线模式的流水线。
使用场景:
- 用户请求:“创建多项目流水线……”“触发其他流水线……”
- 场景:单体仓库、微服务、编排流水线
流程:
- 确定流水线编排需求
- 使用
assets/templates/multi-project.yml或父子流水线模板 - 配置适当的制品传递
- 适时实施并行执行
- 始终使用 devops-skills:gitlab-ci-validator 技能进行验证
示例(父子流水线):
# Parent pipeline
stages:
- trigger
generate-child-pipeline:
stage: trigger
script:
- echo "Generating child pipeline config"
- |
cat > child-pipeline.yml <<EOF
stages:
- build
child-job:
stage: build
script:
- echo "Running child job"
EOF
artifacts:
paths:
- child-pipeline.yml
trigger-child:
stage: trigger
trigger:
include:
- artifact: child-pipeline.yml
job: generate-child-pipeline
strategy: depend
needs: [generate-child-pipeline]
5. 生成基于模板的配置
使用 extends、YAML 锚点和 includes 创建可复用模板。
使用场景:
- 用户请求:“创建可复用模板……”“构建模块化流水线配置……”
- 场景:模板库、DRY 配置、共享 CI/CD 逻辑
流程:
- 确定要提取的通用模式
- 创建隐藏作业(以 . 开头)
- 使用
extends关键字实现继承 - 使用
include将内容整理到不同文件中 - 始终使用 devops-skills:gitlab-ci-validator 技能进行验证
示例:
# Hidden template jobs (include timeout in templates)
.node-template:
image: node:20-alpine
timeout: 15 minutes # Default timeout for jobs using this template
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
before_script:
- npm ci
interruptible: true
.deploy-template:
timeout: 10 minutes # Deploy jobs should have explicit timeout
before_script:
- echo "Deploying to ${ENVIRONMENT}"
after_script:
- echo "Deployment complete"
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
interruptible: false # Deploys should not be interrupted
# Actual jobs using templates
build:
extends: .node-template
stage: build
script:
- npm run build
deploy-staging:
extends: .deploy-template
stage: deploy
variables:
ENVIRONMENT: staging
script:
- ./deploy.sh staging
resource_group: staging
6. 处理 GitLab CI/CD 文档查询
仅当本地参考资料未涵盖所请求的功能或版本相关行为时,才使用此流程。
检测:
- 用户提及特定 GitLab 功能(例如“Auto DevOps”、“SAST”、“依赖扫描”)
- 用户请求与 GitLab 模板集成
- 流水线需要特定的 GitLab runner 功能
流程:
-
识别功能:
- 提取 GitLab 功能或模板名称
- 判断是否需要版本相关信息
-
优先检查本地参考资料(Tier 1/Tier 2):
references/common-patterns.mdreferences/gitlab-ci-reference.mdreferences/security-guidelines.md
-
需要外部查询时,优先使用 Context7:
- 解析库:
mcp__context7__resolve-library-id - 查询文档:
mcp__context7__query-docs - 优先选择 GitLab 官方文档/库文档,而非二手来源
- 解析库:
-
Context7 不可用或信息不足时,回退到网络搜索:
- 使用
web.search_query - 查询格式:
"GitLab CI/CD [feature] documentation" - 优先选择来自
docs.gitlab.com的结果
- 使用
-
必要时打开并提取特定文档页面的内容:
- 对选定的文档页面使用
web.open - 获取所需语法、变量和版本限制
- 对选定的文档页面使用
-
分析查到的文档,了解:
- 当前推荐的方法
- 所需变量和配置
- 模板包含语法
- 最佳实践和安全建议
- 用法示例
-
网络工具不可用(离线/受限环境)时:
- 仅继续使用本地参考资料
- 说明无法进行外部版本验证
- 在最终输出中添加版本假设说明
-
根据查到的信息生成流水线:
- 使用正确的模板包含语法
- 配置所需变量
- 添加安全最佳实践
- 添加关于版本和选择的注释
GitLab 模板示例:
# Include GitLab's security templates (use Jobs/ prefix for current templates)
include:
- template: Jobs/SAST.gitlab-ci.yml
- template: Jobs/Dependency-Scanning.gitlab-ci.yml
# Customize SAST behavior via global variables
# Note: Set variables globally rather than overriding template jobs
# to avoid validation issues with partial job definitions
variables:
SAST_EXCLUDED_PATHS: "spec, test, tests, tmp, node_modules"
DS_EXCLUDED_PATHS: "node_modules, vendor"
SECURE_LOG_LEVEL: "info"
重要: 使用 GitLab 模板的
include时,被包含的作业已在模板中完整定义。如果需要自定义这些作业,优先设置全局变量,而不要创建部分作业覆盖(因为验证器无法解析被包含的模板,导致本地验证失败)。GitLab 会在运行时合并配置,但本地验证器只能看到你的.gitlab-ci.yml文件。
验证工作流
关键: 在向用户展示之前,必须验证每个生成的 GitLab CI/CD 配置。
验证流程
-
**主要验证路径:**生成完整流水线后,调用
devops-skills:gitlab-ci-validator技能:Skill: devops-skills:gitlab-ci-validator -
脚本备用路径(无法调用验证器技能时):
PIPELINE_FILE="<generated-output-path>"- 将
PIPELINE_FILE设置为生成文件的确切路径(例如pipelines/review.yml或.gitlab-ci.yml)。 - 如果该文件不存在,则立即失败:
if [[ ! -f "$PIPELINE_FILE" ]]; then echo "ERROR: CI file not found: $PIPELINE_FILE" >&2 exit 1 fi
# From repository root bash devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"# From skills/gitlab-ci-generator directory bash ../gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"- 如果脚本不可执行:
chmod +x devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh - 如果有 GitLab 项目上下文,可选用 API lint 作为备用方案:
jq --null-input --arg yaml "$(<"$PIPELINE_FILE")" '.content=$yaml' \ | curl --header "Content-Type: application/json" \ --url "https://gitlab.com/api/v4/projects/:id/ci/lint?include_merged_yaml=true" \ --data @-
- 将
-
人工备用路径(仅在主要路径和脚本路径都不可用时):
- 手动检查 YAML 是否有效、阶段/作业引用是否正确,以及是否存在明显的机密信息泄露。
- 将输出标记为:
Validation status: Manual fallback (not fully verified)。 - 如果无法有把握地排除严重/高风险问题,则不得声称其已达到生产就绪状态。
-
验证器技能/脚本的检查项:
- 验证 YAML 语法
- 检查是否符合 GitLab CI/CD 架构
- 验证作业引用和依赖关系
- 检查是否违反最佳实践
- 执行安全扫描
- 报告任何错误、警告或问题
-
分析验证结果,并根据严重程度采取相应措施:
严重程度 必须采取的措施 CRITICAL 呈现前必须修复。流水线已损坏或存在严重安全问题。 HIGH 呈现前必须修复。存在重大安全或功能问题。 MEDIUM 呈现前应该修复。应用修复,或说明为何不适用。 LOW 可以修复或说明情况。告知用户相关建议。 SUGGESTIONS 评估并在有益时应用。无需修复。 -
修复并重新验证循环(存在严重/高风险问题时必须执行):
While validation has CRITICAL or HIGH issues: 1. Edit the generated file to fix the issue 2. Re-run validation 3. Repeat until no CRITICAL or HIGH issues remain -
呈现给用户前,确保:
- 严重问题为零
- 高风险问题为零
- 中等问题已修复,或已说明为何可以接受
- 已说明低风险问题和建议
-
呈现经过验证的配置时:
- 明确说明验证状态
- 说明使用的验证路径(技能、脚本备用路径或人工备用路径)
- 列出任何遗留的中/低风险问题并作出解释
- 包含模板/版本时效性说明
- 提供使用说明
- 说明所做的权衡
严重/高风险门槛要求严格,对于声称可用于生产的配置,绝不可省略。
验证通过标准
流水线达到可呈现状态的条件:
- ✅ 已执行验证路径(验证器技能或脚本备用路径)
- ✅ 语法验证:通过
- ✅ 安全扫描:没有严重或高风险问题
- ✅ 已检查最佳实践(可接受带有说明的警告)
流水线未达到可呈现状态的条件:
- ❌ 存在任何语法错误
- ❌ 存在任何严重安全问题
- ❌ 存在任何高风险安全问题
- ❌ 作业引用无效
- ❌ 仅使用人工备用路径,且无法排除严重/高风险问题
何时跳过验证
仅在以下情况下跳过验证:
- 生成部分代码片段(而非完整文件)
- 创建用于文档的示例
- 用户明确要求跳过验证
处理中等严重性问题(必须输出)
当验证器报告中等严重性问题时,您必须修复这些问题,或者解释为什么可以接受。此解释必须包含在输出中。
处理中等严重性问题的必需格式:
## Validation Issues Addressed
### MEDIUM Severity Issues
| Issue | Status | Explanation |
|-------|--------|-------------|
| [Issue code] | Fixed/Acceptable | [Why it was fixed OR why it's acceptable] |
中等严重性问题说明示例:
## Validation Issues Addressed
### MEDIUM Severity Issues
| Issue | Status | Explanation |
|-------|--------|-------------|
| `image-variable-no-digest` | Acceptable | Using `python:${PYTHON_VERSION}-alpine` allows flexible version management via CI/CD variables. The PYTHON_VERSION variable is controlled internally and pinned to "3.12". SHA digest pinning would require updating the digest with every image update, adding maintenance burden without significant security benefit for this use case. |
| `pip-without-hashes` | Acceptable | This pipeline installs well-known packages (pytest, flake8) from PyPI. Using `--require-hashes` would require maintaining hash files for all transitive dependencies. For internal CI/CD, the security trade-off is acceptable. For higher security environments, consider using a private PyPI mirror with verified packages. |
| `git-strategy-none` | Acceptable | The `stop-staging` and `rollback-production` jobs use `GIT_STRATEGY: none` because they only run kubectl commands that don't require source code. The scripts are inline in the YAML (not from the repo), so there's no risk of executing untrusted code. |
何时修复与接受:
| 情况 | 操作 |
|---|---|
| 生产环境/高安全性环境 | 修复问题 |
| 问题很容易修复,且没有负面影响 | 修复问题 |
| 修复会显著增加复杂性 | 接受并说明原因 |
| 修复需要外部变更(例如 CI/CD 变量) | 接受并说明原因 |
| 在此情境下问题属于误报 | 接受并说明原因 |
审核建议(必须输出)
当验证器提供建议时,您必须简要确认已收到建议,并说明是否应该采纳。
必需格式:
## Validator Suggestions Review
| Suggestion | Recommendation | Reason |
|------------|----------------|--------|
| [suggestion] | Apply/Skip | [Why] |
审核建议示例:
## Validator Suggestions Review
| Suggestion | Recommendation | Reason |
|------------|----------------|--------|
| `missing-retry` on test jobs | Skip | Test jobs are deterministic and don't interact with external services. Retry would mask flaky tests rather than fail fast. |
| `parallel-opportunity` for test-unit | Apply if beneficial | Could be added if pytest supports sharding. Add `parallel: 3` with `pytest --shard=${CI_NODE_INDEX}/${CI_NODE_TOTAL}` if test suite is large enough to benefit. |
| `dag-optimization` for stop-staging | Skip | This job is manual and only runs on environment cleanup. DAG optimization wouldn't provide meaningful speedup. |
| `no-dependency-proxy` | Apply for production | Consider using `$CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX` to avoid Docker Hub rate limits. Requires GitLab Premium. |
| `environment-no-url` for rollback | Skip | Rollback jobs don't deploy new versions, so a URL would be misleading. |
| `missing-coverage` for lint job | Skip | Linting doesn't produce coverage data. This is a false positive. |
模板与版本说明(必须输出)
验证结果之后,请简要说明模板和文档假设的新鲜度。
必需格式:
## Template and Version Notes
- **Template base:** [assets/templates/<file>.yml]
- **Template customization scope:** [what changed from template]
- **Version/doc basis:** [Context7, docs.gitlab.com, or local references only]
- **Freshness note:** [exact date checked, or "external lookup unavailable"]
- **Version-sensitive assumptions:** [if any]
示例:
## Template and Version Notes
- **Template base:** assets/templates/docker-build.yml
- **Template customization scope:** Added unit-test stage and environment-specific deploy rules
- **Version/doc basis:** docs.gitlab.com include-template docs + local references
- **Freshness note:** Verified template syntax on 2026-02-28
- **Version-sensitive assumptions:** Uses `Jobs/SAST.gitlab-ci.yml` template path
使用说明模板(必须输出)
展示经过验证的流水线后,您必须提供使用说明。此项为必需内容。
必需格式:
## Usage Instructions
### Required CI/CD Variables
Configure these variables in **Settings → CI/CD → Variables**:
| Variable | Description | Masked | Protected |
|----------|-------------|--------|-----------|
| [VARIABLE_NAME] | [Description] | Yes/No | Yes/No |
### Setup Steps
1. [First setup step]
2. [Second setup step]
...
### Pipeline Behavior
- **On push to `develop`:** [What happens]
- **On push to `main`:** [What happens]
- **On tag `vX.Y.Z`:** [What happens]
### Customization
[Any customization notes]
使用说明示例:
## Usage Instructions
### Required CI/CD Variables
Configure these variables in **Settings → CI/CD → Variables**:
| Variable | Description | Masked | Protected |
|----------|-------------|--------|-----------|
| `KUBE_CONTEXT` | Kubernetes cluster context name | No | Yes |
| `KUBE_NAMESPACE_STAGING` | Staging namespace (default: staging) | No | No |
| `KUBE_NAMESPACE_PRODUCTION` | Production namespace (default: production) | No | Yes |
**Note:** `CI_REGISTRY_USER`, `CI_REGISTRY_PASSWORD`, and `CI_REGISTRY` are automatically provided by GitLab.
### Kubernetes Integration Setup
1. **Enable Kubernetes integration** in **Settings → Infrastructure → Kubernetes clusters**
2. **Add your cluster** using the agent-based or certificate-based method
3. **Create namespaces** for staging and production if they don't exist:
```bash
kubectl create namespace staging
kubectl create namespace production
- 确保目标命名空间中存在部署,然后再运行流水线
流水线行为
- **推送到
develop时:**运行测试 → 构建 Docker 镜像 → 自动部署到暂存环境 - **推送到
main时:**运行测试 → 构建 Docker 镜像 → 手动部署到生产环境 - **推送标签
vX.Y.Z时:**运行测试 → 构建 Docker 镜像 → 手动部署到生产环境
自定义
- 更新
APP_NAME变量,使其与 Kubernetes 部署名称一致 - 修改
deploy-staging和deploy-production作业中的环境 URL - 取消模板中 Helm 作业的注释,以添加 Helm 部署
## Best Practices to Enforce
Reference `references/best-practices.md` for comprehensive guidelines. Key principles:
### Mandatory Standards
1. **Security First:**
- Pin Docker images to specific versions (not :latest)
- Use masked variables for secrets ($CI_REGISTRY_PASSWORD should be masked)
- Never expose secrets in logs
- Validate inputs and sanitize variables
- Use protected variables for sensitive environments
2. **Performance:**
- Implement caching for dependencies (ALWAYS for npm, pip, maven, etc.)
- Use `needs` keyword for DAG optimization (ALWAYS when jobs have dependencies)
- Set artifact expiration to avoid storage bloat (ALWAYS set `expire_in`)
- Use `parallel` execution *when applicable* (only if test framework supports sharding)
- Minimize unnecessary artifact passing (use `artifacts: false` in `needs` when not needed)
3. **Reliability:**
- **Set explicit `timeout` for ALL jobs** (prevents hanging jobs, typically 10-30 minutes)
- Even when using `default` or `extends` for timeout inheritance, add explicit `timeout` to each job
- This improves readability and avoids validator warnings about missing timeout
- Example: A job using `.deploy-template` should still have `timeout: 15 minutes` explicitly set
- Add retry logic for flaky operations (network calls, external API interactions)
- Use `allow_failure` appropriately for non-critical jobs (linting, optional scans)
- Use `resource_group` for deployment jobs (prevents concurrent deployments)
- Add `interruptible: true` for test jobs (allows cancellation when new commits push)
4. **Naming:**
- Job names: Descriptive, kebab-case (e.g., "build-application", "test-unit")
- Stage names: Short, clear (e.g., "build", "test", "deploy")
- Variable names: UPPER_SNAKE_CASE for environment variables
- Environment names: lowercase (e.g., "production", "staging")
5. **Configuration Organization:**
- Use `extends` for reusable configuration (PREFERRED over YAML anchors for GitLab CI)
- Use `include` for modular pipeline files (organize large pipelines into multiple files)
- Use `rules` instead of deprecated only/except (ALWAYS)
- Define `default` settings for common configurations (image, timeout, cache, tags)
- Use YAML anchors *only when necessary* for complex repeated structures within a single file
- Note: `extends` is preferred because it provides better visualization in GitLab UI
6. **Error Handling:**
- Set appropriate timeout values (ALWAYS - prevents hanging jobs)
- Configure retry behavior for flaky operations (network calls, external APIs)
- Use `allow_failure: true` for non-blocking jobs (linting, optional scans)
- Add cleanup steps with `after_script` *when needed* (e.g., stopping test containers, cleanup)
- Implement notification mechanisms *when required* (e.g., Slack integration for deployment failures)
## Resources
### References (Tiered Loading)
- `references/best-practices.md` (**Tier 1: required for all**) - Comprehensive GitLab CI/CD best practices
- Security patterns, performance optimization
- Pipeline design, configuration organization
- Common patterns and anti-patterns
- **Use this:** When implementing any GitLab CI/CD resource
- `references/common-patterns.md` (**Tier 1: required for all**) - Frequently used pipeline patterns
- Basic CI pipeline patterns
- Docker build and push patterns
- Deployment patterns (K8s, cloud platforms)
- Multi-project and parent-child patterns
- **Use this:** When selecting which pattern to use
- `references/gitlab-ci-reference.md` (**Tier 2: required for Full mode**) - GitLab CI/CD YAML syntax reference
- Complete keyword reference
- Job configuration options
- Rules and conditional execution
- Variables and environments
- **Use this:** For syntax and keyword details
- `references/security-guidelines.md` (**Tier 2: required for Full mode**) - Security best practices
- Secrets management
- Image security
- Script security
- Artifact security
- **Use this:** For security-sensitive configurations
### Assets (Templates to Customize)
- `assets/templates/basic-pipeline.yml` - Complete basic pipeline template
- `assets/templates/docker-build.yml` - Docker build pipeline template
- `assets/templates/kubernetes-deploy.yml` - Kubernetes deployment template
- `assets/templates/multi-project.yml` - Multi-project orchestration template
**How to use templates:**
1. Copy the relevant template structure
2. Replace all `[PLACEHOLDERS]` with actual values
3. Customize logic based on user requirements
4. Remove unnecessary sections
5. Validate the result
## Typical Workflow Example
**User request:** "Create a CI/CD pipeline for a Node.js app with testing and Docker deployment"
**Process:**
1. ✅ Understand requirements:
- Node.js application
- Run tests (unit, lint)
- Build Docker image
- Deploy to container registry
- Trigger on push and merge requests
2. ✅ Reference resources:
- Check `references/best-practices.md` for pipeline structure
- Check `references/common-patterns.md` for Node.js + Docker pattern
- Use `assets/templates/docker-build.yml` as base
3. ✅ Generate pipeline:
- Define stages (build, test, dockerize, deploy)
- Create build job with caching
- Create test jobs (unit, lint) with needs optimization
- Create Docker build job
- Add proper artifact management
- Pin Docker images to versions
- Include proper secrets handling
4. ✅ Validate:
- Invoke `devops-skills:gitlab-ci-validator` skill
- Fix any reported issues
- Re-validate if needed
5. ✅ Present to user:
- Show validated pipeline
- Explain key sections
- Provide usage instructions
- Mention successful validation
## Common Pipeline Patterns
### Basic Three-Stage Pipeline
```yaml
stages:
- build
- test
- deploy
build-job:
stage: build
script: make build
test-job:
stage: test
script: make test
deploy-job:
stage: deploy
script: make deploy
when: manual
使用 Needs 的 DAG 流水线
stages:
- build
- test
- deploy
build-frontend:
stage: build
script: npm run build:frontend
build-backend:
stage: build
script: npm run build:backend
test-frontend:
stage: test
needs: [build-frontend]
script: npm test:frontend
test-backend:
stage: test
needs: [build-backend]
script: npm test:backend
deploy:
stage: deploy
needs: [test-frontend, test-backend]
script: make deploy
使用 Rules 的条件执行
deploy-staging:
script: deploy staging
rules:
- if: $CI_COMMIT_BRANCH == "develop"
when: always
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
deploy-production:
script: deploy production
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
- when: never
矩阵并行作业
test:
parallel:
matrix:
- NODE_VERSION: ['18', '20', '22']
OS: ['ubuntu', 'alpine']
image: node:${NODE_VERSION}-${OS}
script:
- npm test
错误消息与故障排除
如果 devops-skills:gitlab-ci-validator 报告错误:
- **语法错误:**修复 YAML 格式、缩进或结构
- **作业引用错误:**确保 needs/dependencies 中引用的作业确实存在
- **阶段错误:**确认所有作业阶段都已在 stages 列表中定义
- **规则错误:**检查 rules 语法和变量引用
- **安全警告:**处理硬编码密钥和镜像固定问题
如果找不到 GitLab 文档:
- 首先尝试 Context7:
mcp__context7__resolve-library-id->mcp__context7__query-docs - 如有需要,使用限定在
docs.gitlab.com范围内的web.search_query - 使用
web.open打开特定页面,并仅提取所需的语法/变量 - 如果处于离线状态,请使用本地参考资料继续操作,并注明版本假设
交付前检查清单
**必须:**在向用户展示任何生成的流水线之前,核实以下所有项目:
模式与参考资料
- 已选择复杂度模式(
Targeted、Lightweight或Full) - 对于 Targeted 模式:仅加载直接相关的文件/参考资料
- 对于 Lightweight/Full 模式:生成前已阅读
references/best-practices.md - 对于 Lightweight/Full 模式:生成前已阅读
references/common-patterns.md - 对于 Lightweight/Full 模式:已阅读
assets/templates/中适用于该流水线类型的模板 - 对于 Full 模式:已阅读
references/gitlab-ci-reference.md - 对于 Full 模式:已阅读
references/security-guidelines.md - 对于 Lightweight/Full 模式,输出明确的确认声明
已应用的生成标准
- 所有 Docker 镜像均固定为特定版本(不使用
:latest) - 所有作业均显式设置
timeout(通常为 10–30 分钟) - 如果定义了
default块,则其中包含timeout - 隐藏模板(
.template-name)包含timeout - 已为依赖项安装配置缓存
- 在适当情况下使用
needs关键字优化 DAG - 使用
rules(而非已弃用的only/except) - 为部署作业配置
resource_group - 为构件设置
expire_in - 密钥使用经过遮罩的 CI/CD 变量(不硬编码)
已完成验证
- 通过
devops-skills:gitlab-ci-validator或脚本回退方案执行验证 - CRITICAL 问题为零
- HIGH 问题为零
- 已处理 MEDIUM 问题(已修复,或按要求的格式在输出中说明)
- 已确认 LOW 问题(在输出中列出)
- 已审查建议(使用要求的格式)
- 任何修复后均已重新验证
- 如果只有手动回退方案可用:输出已标记为未完全验证
已准备好呈现
- 已清楚说明验证状态
- 已清楚说明验证路径(技能、脚本回退或手动回退)
- 已说明 MEDIUM/LOW 问题(使用表格格式)
- 已提供建议审查结果(使用表格格式)
- 已提供模板和版本说明(使用要求的格式)
- 已提供使用说明(包含要求的章节)
- 已说明关键章节
如果有任何复选框未勾选,请勿呈现流水线。请先完成缺失步骤。
必需的输出章节
根据所选模式,使用最精简的有效输出配置。
完整模式(完整/复杂流水线):
- 参考分析已完成(来自步骤 3)
- 生成的流水线(
.gitlab-ci.yml内容) - 验证结果摘要(通过/失败状态)
- 已处理的验证问题(MEDIUM 问题表格)
- 验证器建议审查(建议表格)
- 模板和版本说明(模板基础 + 新鲜度/版本假设)
- 使用说明(变量、设置、行为)
轻量模式(完整/简单流水线):
- 参考分析已完成(轻量)
- 生成的流水线
- 验证结果摘要
- 模板和版本说明
- 使用说明
- 仅在存在 MEDIUM 问题时添加 已处理的验证问题。
- 仅在存在建议时添加 验证器建议审查。
定向模式(审查/问答/代码片段/针对性修复):
- 仅提供直接请求的内容/答案及简要说明。
- 如果未运行验证,请说明验证/回退情况。
- 不要强行添加完整的流水线生成章节。
完成标准
满足以下条件时,此技能执行即告完成:
- 简单请求使用轻量模式,无需加载不必要的第二层内容。
- 复杂请求使用完整模式,加载第二层参考资料并完成确认。
- 验证在声称可用于生产之前,严格检查 Critical/High 关卡。
- 输出包含模板/版本新鲜度说明和使用说明。
- 明确说明任何回退路径,不隐瞒验证缺口。
摘要
生成 GitLab CI/CD 流水线时,始终遵循以下顺序:
- 分类复杂度 - 选择
Targeted、Lightweight或Full模式。 - 加载参考资料 - 分层加载:
- 对于
Targeted模式,仅加载直接相关的文件。 - 对于
Lightweight/Full模式,加载:references/best-practices.mdreferences/common-patterns.md- 以及
assets/templates/中合适的模板
- 对于
Full模式,还要加载:references/gitlab-ci-reference.mdreferences/security-guidelines.md
- 对于
- 确认 - 根据模式要求,输出针对性响应或 Lightweight/Full 参考资料分析。
- 生成 - 使用模板并遵循标准(安全性、缓存、命名,以及为所有作业明确设置超时时间)。
- 按需查阅文档 - 优先使用 Context7,然后使用
web.search_query/web.open;受限时提供离线回退说明。 - 验证 - 使用
devops-skills:gitlab-ci-validator;必要时使用脚本回退方案。 - 修复 - 解决所有 Critical/High 问题,并处理 Medium 问题。
- 核对清单 - 确认交付前清单中的所有项目均已完成。
- 呈现 - 提供输出,并附上验证摘要、模板/版本说明和使用说明。
生成的 GitLab CI/CD 流水线应当:
- ✅ 使用固定版本的镜像并妥善处理密钥,确保安全
- ✅ 遵循当前最佳实践和约定
- ✅ 正确组织配置(extends、includes)
- ✅ 优化性能(缓存、needs、DAG)
- ✅ 附有完善的使用说明
- ✅ 已通过验证,且不存在 Critical/High 问题
- ✅ 可用于生产环境,且易于维护