gitlab-ci-generator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGitLab CI/CD Pipeline Generator
GitLab CI/CD 流水线生成器
Overview
概述
Generate production-ready GitLab CI/CD pipeline configurations following current best practices, security standards, and naming conventions. All generated resources are automatically validated using the devops-skills:gitlab-ci-validator skill to ensure syntax correctness and compliance with best practices.
遵循当前最佳实践、安全标准和命名规范,生成可用于生产环境的GitLab CI/CD流水线配置。所有生成的资源都会自动使用devops-skills:gitlab-ci-validator工具进行验证,以确保语法正确性和符合最佳实践要求。
Trigger Phrases
触发短语
Use this skill when the user asks for GitLab CI/CD generation requests such as:
- "Create a for..."
.gitlab-ci.yml - "Build a GitLab pipeline for Node/Python/Java..."
- "Add Docker build and deploy jobs in GitLab CI"
- "Set up GitLab parent-child or multi-project pipelines"
- "Include SAST/dependency scanning templates in GitLab CI"
当用户提出以下GitLab CI/CD生成请求时,使用本工具:
- "为……创建一个"
.gitlab-ci.yml - "为Node/Python/Java……构建GitLab流水线"
- "在GitLab CI中添加Docker构建与部署任务"
- "设置GitLab父子流水线或多项目流水线"
- "在GitLab CI中包含SAST/依赖扫描模板"
Execution Model
执行模型
Follow this deterministic flow in order:
- Classify request complexity (,
targeted, orlightweight).full - Load only the required reference tier for that complexity.
- Output the matching response profile for the selected mode.
- For complete pipeline generation, start from the closest template and customize.
- Validate complete pipelines with strict Critical/High gates.
- Present output with validation status and template/version notes.
If tooling is unavailable, use the documented fallback branch and report it explicitly.
按以下确定性流程执行:
- 对请求复杂度进行分类(、
targeted或lightweight)。full - 仅加载对应复杂度所需的参考层级。
- 输出与所选模式匹配的响应模板。
- 若生成完整流水线,从最匹配的模板开始进行自定义。
- 对完整流水线进行严格的Critical/High级别验证。
- 输出时附带验证状态以及模板/版本说明。
若工具不可用,使用文档中记录的备选分支,并明确告知用户。
Mode Routing (Quick Decision)
模式路由(快速决策)
| Request shape | Mode | Required references | Output profile |
|---|---|---|---|
| Simple single-file pipeline with common jobs/stages and low risk | Lightweight | Tier 1 (+ Tier 2 only if needed) | Lightweight confirmation + compact final sections |
Multi-environment deploy, advanced | Full | Tier 1 + Tier 2 (Tier 3 only if needed) | Full confirmation + full final sections |
| Review/Q&A/snippet/focused fix (not full file generation) | Targeted | Only directly relevant files | Concise targeted response (no full boilerplate) |
When uncertain on a complete-generation request, route to Full mode.
| 请求类型 | 模式 | 所需参考 | 输出模板 |
|---|---|---|---|
| 包含通用任务/阶段的简单单文件流水线,风险较低 | Lightweight(轻量) | 第1层级(必要时加第2层级) | 轻量确认信息 + 精简的最终配置片段 |
多环境部署、高级 | Full(完整) | 第1层级 + 第2层级(必要时加第3层级) | 完整确认信息 + 完整的最终配置片段 |
| 评审/问答/代码片段/针对性修复(非完整文件生成) | Targeted(针对性) | 仅加载直接相关的文件 | 简洁的针对性响应(无完整模板代码) |
若对完整生成请求的复杂度不确定,默认使用Full模式。
MANDATORY PRE-GENERATION STEPS
生成前的强制步骤
CRITICAL: Before generating any complete GitLab CI/CD pipeline, complete these steps.
关键: 在生成任何GitLab CI/CD完整流水线之前,必须完成以下步骤。
Step 1: Classify Complexity (REQUIRED)
步骤1:复杂度分类(必填)
| Mode | Use When | Minimum Confirmation |
|---|---|---|
| Targeted | Review/Q&A/snippet/focused fix where full pipeline generation is not requested | Concise targeted response |
| Lightweight | Simple single-file pipeline, common stages/jobs, no advanced GitLab features, no sensitive deploy/security customization | Lightweight confirmation |
| Full | Multi-environment deploys, includes/templates, advanced | Full confirmation |
When uncertain on a complete-generation request, default to Full mode.
| 模式 | 使用场景 | 最低确认要求 |
|---|---|---|
| Targeted(针对性) | 评审/问答/代码片段/针对性修复,无需生成完整流水线 | 简洁的针对性响应 |
| Lightweight(轻量) | 简单单文件流水线、通用阶段/任务,无需GitLab高级功能,无需敏感部署/安全自定义 | 轻量确认信息 |
| Full(完整) | 多环境部署、包含/模板、高级 | 完整确认信息 |
若对完整生成请求的复杂度不确定,默认使用Full模式。
Step 2: Load References by Tier (REQUIRED)
步骤2:按层级加载参考资源(必填)
Use an open/read action to load references based on the selected mode.
Targeted mode (review/Q&A/snippet/focused fix):
- Load only directly relevant references/templates for the scoped request.
- Do not enforce Full-generation Tier 1/Tier 2 checklist items.
Tier 1 (Required for complete pipeline generation in Lightweight and Full modes):
- - baseline security, performance, naming
references/best-practices.md - - starting pattern selection
references/common-patterns.md - Matching template from :
assets/templates/- Docker pipelines ->
assets/templates/docker-build.yml - Kubernetes deployments ->
assets/templates/kubernetes-deploy.yml - Multi-project pipelines ->
assets/templates/multi-project.yml - Basic pipelines ->
assets/templates/basic-pipeline.yml
- Docker pipelines ->
Tier 2 (Required for Full mode; optional for Lightweight mode):
- - keyword/syntax edge cases
references/gitlab-ci-reference.md - - security-sensitive controls
references/security-guidelines.md
Tier 3 (Conditional external docs lookup):
- Use only when local references do not cover requested features or version-specific behavior.
- Follow the lookup flow in "Handling GitLab CI/CD Documentation Lookup."
If a required local reference or template is unavailable:
- Report the exact missing path.
- Continue with available references and mark assumptions explicitly.
- Do not claim production-ready confidence until missing critical inputs are resolved.
根据所选模式,使用读取操作加载参考资源。
Targeted模式(评审/问答/代码片段/针对性修复):
- 仅加载与特定请求直接相关的参考/模板。
- 无需强制执行完整生成所需的第1/第2层级检查项。
第1层级(Lightweight和Full模式下完整流水线生成的必填项):
- - 基础安全、性能、命名规范
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流水线 ->
第2层级(Full模式必填;Lightweight模式可选):
- - 关键字/语法边缘情况
references/gitlab-ci-reference.md - - 安全敏感控制措施
references/security-guidelines.md
第3层级(条件性外部文档查询):
- 仅当本地参考资源未覆盖请求的功能或特定版本行为时使用。
- 遵循“GitLab CI/CD文档查询处理”中的流程。
若所需的本地参考资源或模板不可用:
- 报告确切的缺失路径。
- 使用可用的参考资源继续,并明确标记假设内容。
- 在缺失关键输入未解决前,不得声称配置可用于生产环境。
Step 3: Confirm Understanding (EXPLICIT OUTPUT REQUIRED)
步骤3:确认理解(必须输出明确内容)
Lightweight Confirmation Mode
Lightweight确认模式
Use for simple requests only.
Required format:
markdown
undefined仅用于简单请求。
必填格式:
markdown
undefinedReference Analysis Complete (Lightweight)
参考分析完成(轻量模式)
Pattern: [Pattern name] from common-patterns.md
Template: [Template file]
Key standards to enforce:
- [2-3 concrete standards]
**Example:**
```markdown模式: [模式名称] 来自common-patterns.md
模板: [模板文件]
需强制执行的关键标准:
- [2-3条具体标准]
**示例:**
```markdownReference 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 instead of deprecated
rules/onlyexcept
undefined模式: 基础构建-测试-部署 来自common-patterns.md
模板: assets/templates/basic-pipeline.yml
需强制执行的关键标准:
- 固定运行时镜像版本(不使用)
:latest - 添加明确的任务超时时间
- 使用替代已弃用的
rules/onlyexcept
undefinedFull Confirmation Mode
Full确认模式
Use for complex or security-sensitive requests.
Required format:
markdown
undefined用于复杂或安全敏感的请求。
必填格式:
markdown
undefinedReference 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]
**Example:**
```markdown识别的流水线模式: [模式名称] 来自common-patterns.md
- [简要说明该模式匹配的原因]
需应用的最佳实践:
- [列出3-5条与本流水线相关的关键最佳实践]
安全准则:
- [列出需实现的安全措施]
模板基础: [模板文件名]
- [将对该模板进行哪些自定义]
**示例:**
```markdownReference 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 keyword
needs - Set explicit timeout on all jobs (15-20 minutes)
- Use for deployment jobs
resource_group
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
**Skipping confirmation is not allowed for complete pipeline generation.**
---识别的流水线模式: Docker构建 + Kubernetes部署 来自common-patterns.md
- 用户需要将容器化应用部署到K8s集群,包含预发布/生产环境
需应用的最佳实践:
- 固定所有Docker镜像到特定版本(不使用)
:latest - 为pip依赖项启用缓存
- 使用关键字实现DAG优化
needs - 为所有任务设置明确的超时时间(15-20分钟)
- 为部署任务使用
resource_group
安全准则:
- 对敏感信息(KUBE_CONTEXT、镜像仓库凭证)使用掩码化CI/CD变量
- 包含使用Trivy的容器扫描
- 绝不在日志中暴露敏感信息
模板基础: assets/templates/docker-build.yml + assets/templates/kubernetes-deploy.yml
- 合并Docker构建模式与K8s kubectl部署流程
- 添加Python特定的测试任务
**完整流水线生成时不允许跳过确认步骤。**
---Core Capabilities
核心能力
1. Generate Basic CI/CD Pipelines
1. 生成基础CI/CD流水线
Create complete, production-ready files with proper structure, security best practices, and efficient CI/CD patterns.
.gitlab-ci.ymlWhen to use:
- User requests: "Create a GitLab pipeline for...", "Build a CI/CD pipeline...", "Generate GitLab CI config..."
- Scenarios: CI/CD pipelines, automated testing, build automation, deployment pipelines
Process:
- Understand the user's requirements (what needs to be automated)
- Identify stages, jobs, dependencies, and artifacts
- Use as structural foundation
assets/templates/basic-pipeline.yml - Reference for implementation patterns
references/best-practices.md - Reference for standard pipeline patterns
references/common-patterns.md - Generate the pipeline following these principles:
- Use semantic stage and job names
- Pin Docker images to specific versions (not :latest)
- Implement proper secrets management with masked variables
- Use caching for dependencies to improve performance
- Implement proper artifact handling with expiration
- Use keyword for DAG optimization when appropriate
needs - Add proper error handling with retry and allow_failure
- Use instead of deprecated only/except
rules - Set explicit for all jobs (10-30 minutes typically)
timeout - Add meaningful job descriptions in comments
- ALWAYS validate the generated pipeline using the devops-skills:gitlab-ci-validator skill
- If validation fails, fix the issues and re-validate
Example structure:
yaml
undefined创建结构规范、符合安全最佳实践且高效的完整可生产文件。
.gitlab-ci.yml使用场景:
- 用户请求:"为……创建GitLab流水线"、"构建CI/CD流水线"、"生成GitLab CI配置"
- 适用场景:CI/CD流水线、自动化测试、构建自动化、部署流水线
流程:
- 理解用户需求(需要自动化的内容)
- 确定阶段、任务、依赖关系和产物
- 使用作为结构基础
assets/templates/basic-pipeline.yml - 参考获取实现模式
references/best-practices.md - 参考获取标准流水线模式
references/common-patterns.md - 遵循以下原则生成流水线:
- 使用语义化的阶段和任务名称
- 固定Docker镜像到特定版本(不使用:latest)
- 使用掩码化变量实现正确的敏感信息管理
- 为依赖项启用缓存以提升性能
- 实现带过期时间的产物管理
- 适当情况下使用关键字进行DAG优化
needs - 添加带重试和允许失败的错误处理
- 使用替代已弃用的only/except
rules - 为所有任务设置明确的(通常为10-30分钟)
timeout - 在注释中添加有意义的任务描述
- 必须使用devops-skills:gitlab-ci-validator工具对生成的流水线进行验证
- 若验证失败,修复问题后重新验证
示例结构:
yaml
undefinedBasic CI/CD Pipeline
Basic CI/CD Pipeline
Builds, tests, and deploys the application
Builds, tests, and deploys the application
stages:
- build
- test
- deploy
stages:
- build
- test
- deploy
Global variables
Global variables
variables:
NODE_VERSION: "20"
DOCKER_DRIVER: overlay2
variables:
NODE_VERSION: "20"
DOCKER_DRIVER: overlay2
Default settings for all jobs
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
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 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
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 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
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 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
undefineddeploy-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
undefined2. Generate Docker Build Pipelines
2. 生成Docker构建流水线
Create pipelines for building, testing, and pushing Docker images to container registries.
When to use:
- User requests: "Create a Docker build pipeline...", "Build and push Docker images..."
- Scenarios: Container builds, multi-stage Docker builds, registry pushes
Process:
- Understand the Docker build requirements (base images, registries, tags)
- Use as foundation
assets/templates/docker-build.yml - Implement Docker-in-Docker or Kaniko for builds
- Configure registry authentication
- Implement image tagging strategy
- Add security scanning if needed
- ALWAYS validate using devops-skills:gitlab-ci-validator skill
Example:
yaml
stages:
- build
- scan
- push
variables:
DOCKER_DRIVER: overlay2
IMAGE_NAME: $CI_REGISTRY_IMAGE
IMAGE_TAG: $CI_COMMIT_SHORT_SHA创建用于构建、测试并推送Docker镜像到容器仓库的流水线。
使用场景:
- 用户请求:"创建Docker构建流水线"、"构建并推送Docker镜像"
- 适用场景:容器构建、多阶段Docker构建、镜像仓库推送
流程:
- 理解Docker构建需求(基础镜像、仓库、标签)
- 使用作为基础
assets/templates/docker-build.yml - 实现Docker-in-Docker或Kaniko构建方式
- 配置仓库认证
- 实现镜像标签策略
- 若需要添加安全扫描
- 必须使用devops-skills:gitlab-ci-validator工具进行验证
示例:
yaml
stages:
- build
- scan
- push
variables:
DOCKER_DRIVER: overlay2
IMAGE_NAME: $CI_REGISTRY_IMAGE
IMAGE_TAG: $CI_COMMIT_SHORT_SHABuild Docker image
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
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
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
undefinedcontainer-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
undefined3. Generate Kubernetes Deployment Pipelines
3. 生成Kubernetes部署流水线
Create pipelines that deploy applications to Kubernetes clusters.
When to use:
- User requests: "Deploy to Kubernetes...", "Create K8s deployment pipeline..."
- Scenarios: Kubernetes deployments, Helm deployments, kubectl operations
Process:
- Identify the Kubernetes deployment method (kubectl, Helm, Kustomize)
- Use as foundation
assets/templates/kubernetes-deploy.yml - Configure cluster authentication (service accounts, kubeconfig)
- Implement proper environment management
- Add rollback capabilities
- ALWAYS validate using devops-skills:gitlab-ci-validator skill
Example:
yaml
stages:
- build
- deploy创建用于将应用部署到Kubernetes集群的流水线。
使用场景:
- 用户请求:"部署到Kubernetes"、"创建K8s部署流水线"
- 适用场景:Kubernetes部署、Helm部署、kubectl操作
流程:
- 确定Kubernetes部署方式(kubectl、Helm、Kustomize)
- 使用作为基础
assets/templates/kubernetes-deploy.yml - 配置集群认证(服务账号、kubeconfig)
- 实现正确的环境管理
- 添加回滚能力
- 必须使用devops-skills:gitlab-ci-validator工具进行验证
示例:
yaml
stages:
- build
- deployKubernetes deployment job
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
undefineddeploy-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
undefined4. Generate Multi-Project Pipelines
4. 生成多项目流水线
Create pipelines that trigger other projects or use parent-child pipeline patterns.
When to use:
- User requests: "Create multi-project pipeline...", "Trigger other pipelines..."
- Scenarios: Monorepos, microservices, orchestration pipelines
Process:
- Identify the pipeline orchestration needs
- Use or parent-child templates
assets/templates/multi-project.yml - Configure proper artifact passing
- Implement parallel execution where appropriate
- ALWAYS validate using devops-skills:gitlab-ci-validator skill
Example (Parent-Child):
yaml
undefined创建用于触发其他项目或使用父子流水线模式的流水线。
使用场景:
- 用户请求:"创建多项目流水线"、"触发其他流水线"
- 适用场景:单体仓库、微服务、编排流水线
流程:
- 确定流水线编排需求
- 使用或父子流水线模板
assets/templates/multi-project.yml - 配置正确的产物传递
- 适当情况下实现并行执行
- 必须使用devops-skills:gitlab-ci-validator工具进行验证
示例(父子流水线):
yaml
undefinedParent pipeline
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"
EOFartifacts:
paths:
- child-pipeline.yml
trigger-child:
stage: trigger
trigger:
include:
- artifact: child-pipeline.yml
job: generate-child-pipeline
strategy: depend
needs: [generate-child-pipeline]
undefinedstages:
- 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"
EOFartifacts:
paths:
- child-pipeline.yml
trigger-child:
stage: trigger
trigger:
include:
- artifact: child-pipeline.yml
job: generate-child-pipeline
strategy: depend
needs: [generate-child-pipeline]
undefined5. Generate Template-Based Configurations
5. 生成基于模板的配置
Create reusable templates using extends, YAML anchors, and includes.
When to use:
- User requests: "Create reusable templates...", "Build modular pipeline config..."
- Scenarios: Template libraries, DRY configurations, shared CI/CD logic
Process:
- Identify common patterns to extract
- Create hidden jobs (prefixed with .)
- Use keyword for inheritance
extends - Organize into separate files with
include - ALWAYS validate using devops-skills:gitlab-ci-validator skill
Example:
yaml
undefined使用extends、YAML锚点和include创建可复用的模板。
使用场景:
- 用户请求:"创建可复用模板"、"构建模块化流水线配置"
- 适用场景:模板库、DRY配置、共享CI/CD逻辑
流程:
- 确定需要提取的通用模式
- 创建隐藏任务(以.为前缀)
- 使用关键字实现继承
extends - 使用将配置组织到单独文件中
include - 必须使用devops-skills:gitlab-ci-validator工具进行验证
示例:
yaml
undefinedHidden template jobs (include timeout in templates)
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
.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
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
undefinedbuild:
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
undefined6. Handling GitLab CI/CD Documentation Lookup
6. GitLab CI/CD文档查询处理
Use this flow only when local references do not cover requested features or version-sensitive behavior.
Detection:
- User mentions specific GitLab features (e.g., "Auto DevOps", "SAST", "dependency scanning")
- User requests integration with GitLab templates
- Pipeline requires specific GitLab runner features
Process:
-
Identify the feature:
- Extract the GitLab feature or template name
- Determine if version-specific information is needed
-
Check local references first (Tier 1/Tier 2):
references/common-patterns.mdreferences/gitlab-ci-reference.mdreferences/security-guidelines.md
-
Use Context7 first when external lookup is needed:
- Resolve library:
mcp__context7__resolve-library-id - Query docs:
mcp__context7__query-docs - Prefer GitLab official/library docs over secondary sources
- Resolve library:
-
Fallback to web search when Context7 is unavailable or insufficient:
- Use
web.search_query - Query pattern:
"GitLab CI/CD [feature] documentation" - Prefer results from
docs.gitlab.com
- Use
-
Open and extract from specific docs pages when needed:
- Use for selected documentation pages
web.open - Capture required syntax, variables, and version constraints
- Use
-
Analyze discovered documentation for:
- Current recommended approach
- Required variables and configuration
- Template include syntax
- Best practices and security recommendations
- Example usage
-
If network tools are unavailable (offline/constrained environment):
- Continue using local references only
- State that external version verification could not be performed
- Add a version-assumption note in the final output
-
Generate pipeline using discovered information:
- Use correct template include syntax
- Configure required variables
- Add security best practices
- Include comments about versions and choices
Example with GitLab templates:
yaml
undefined仅当本地参考资源未覆盖请求的功能或特定版本行为时使用此流程。
触发条件:
- 用户提及特定GitLab功能(例如:"Auto DevOps"、"SAST"、"依赖扫描")
- 用户请求与GitLab模板集成
- 流水线需要特定GitLab Runner功能
流程:
-
识别功能:
- 提取GitLab功能或模板名称
- 确定是否需要特定版本的信息
-
首先检查本地参考资源(第1/第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模板示例:
yaml
undefinedInclude GitLab's security templates (use Jobs/ prefix for current templates)
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
include:
- template: Jobs/SAST.gitlab-ci.yml
- template: Jobs/Dependency-Scanning.gitlab-ci.yml
Customize SAST behavior via global variables
Customize SAST behavior via global variables
Note: Set variables globally rather than overriding template jobs
Note: Set variables globally rather than overriding template jobs
to avoid validation issues with partial job definitions
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"
> **Important:** When using `include` with GitLab templates, the included jobs are
> fully defined in the template. If you need to customize them, prefer setting
> variables globally rather than creating partial job overrides (which will fail
> local validation because the validator cannot resolve the included template).
> GitLab merges the configuration at runtime, but local validators only see
> your `.gitlab-ci.yml` file.variables:
SAST_EXCLUDED_PATHS: "spec, test, tests, tmp, node_modules"
DS_EXCLUDED_PATHS: "node_modules, vendor"
SECURE_LOG_LEVEL: "info"
> **重要提示:** 使用`include`引入GitLab模板时,引入的任务在模板中已完整定义。如果需要自定义,优先全局设置变量而非覆盖模板任务(局部任务覆盖会导致本地验证失败,因为验证器无法解析引入的模板)。GitLab会在运行时合并配置,但本地验证器只能看到你的`.gitlab-ci.yml`文件。Validation Workflow
验证工作流
CRITICAL: Every generated GitLab CI/CD configuration MUST be validated before presenting to the user.
关键: 所有生成的GitLab CI/CD配置在呈现给用户之前必须经过验证。
Validation Process
验证流程
-
Primary validation path: after generating a complete pipeline, invoke theskill:
devops-skills:gitlab-ci-validatorSkill: devops-skills:gitlab-ci-validator -
Script fallback path (if validator skill cannot be invoked):bash
PIPELINE_FILE="<generated-output-path>"- Set to the exact generated file path (for example,
PIPELINE_FILEorpipelines/review.yml)..gitlab-ci.yml - Fail fast if that file does not exist:
bash
if [[ ! -f "$PIPELINE_FILE" ]]; then echo "ERROR: CI file not found: $PIPELINE_FILE" >&2 exit 1 fi
bash# From repository root bash devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"bash# From skills/gitlab-ci-generator directory bash ../gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"- If the script is not executable:
bash
chmod +x devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh - Optional API lint fallback when GitLab project context is available:
bash
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 @-
- Set
-
Manual fallback path (only if both primary and script paths are unavailable):
- Run manual checks for YAML validity, stage/job references, and obvious secret exposure.
- Mark output as .
Validation status: Manual fallback (not fully verified) - Do not claim production-ready status if Critical/High risk cannot be confidently ruled out.
-
The validator skill/script checks:
- Validate YAML syntax
- Check GitLab CI/CD schema compliance
- Verify job references and dependencies
- Check for best practices violations
- Perform security scanning
- Report any errors, warnings, or issues
-
Analyze validation results and take action based on severity:
Severity Action Required CRITICAL MUST fix before presenting. Pipeline is broken or severely insecure. HIGH MUST fix before presenting. Significant security or functionality issues. MEDIUM SHOULD fix before presenting. Apply fixes or explain why not applicable. LOW MAY fix or acknowledge. Inform user of recommendations. SUGGESTIONS Review and apply if beneficial. No fix required. -
Fix-and-Revalidate Loop (MANDATORY for Critical/High issues):
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 -
Before presenting to user, ensure:
- Zero CRITICAL issues
- Zero HIGH issues
- MEDIUM issues either fixed OR explained why they're acceptable
- LOW issues and suggestions acknowledged
-
When presenting the validated configuration:
- State validation status clearly
- State validation path used (skill, script fallback, or manual fallback)
- List any remaining MEDIUM/LOW issues with explanations
- Include template/version freshness notes
- Provide usage instructions
- Mention any trade-offs made
Critical/High gate is strict and never optional for production-ready claims.
-
主要验证路径: 生成完整流水线后,调用工具:
devops-skills:gitlab-ci-validatorSkill: devops-skills:gitlab-ci-validator -
脚本回退路径(若无法调用验证工具):bash
PIPELINE_FILE="<generated-output-path>"- 将设置为生成文件的确切路径(例如:
PIPELINE_FILE或pipelines/review.yml)。.gitlab-ci.yml - 如果文件不存在则立即终止:
bash
if [[ ! -f "$PIPELINE_FILE" ]]; then echo "ERROR: CI file not found: $PIPELINE_FILE" >&2 exit 1 fi
bash# From repository root bash devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"bash# From skills/gitlab-ci-generator directory bash ../gitlab-ci-validator/scripts/validate_gitlab_ci.sh "$PIPELINE_FILE"- 如果脚本不可执行:
bash
chmod +x devops-skills-plugin/skills/gitlab-ci-validator/scripts/validate_gitlab_ci.sh - 当有GitLab项目上下文时,可选的API校验回退:
bash
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有效性、阶段/任务引用和明显的敏感信息暴露。
- 将输出标记为。
验证状态:手动回退(未完全验证) - 如果无法排除Critical/High风险,不得声称配置可用于生产环境。
-
验证工具/脚本检查内容:
- 验证YAML语法
- 检查GitLab CI/CD Schema合规性
- 验证任务引用和依赖关系
- 检查最佳实践违规
- 执行安全扫描
- 报告任何错误、警告或问题
-
分析验证结果并根据严重程度采取行动:
严重程度 所需操作 CRITICAL(严重) 呈现给用户前必须修复。流水线已损坏或存在严重安全问题。 HIGH(高) 呈现给用户前必须修复。存在重大安全或功能问题。 MEDIUM(中) 呈现给用户前应修复。修复问题或解释不适用的原因。 LOW(低) 可修复或告知用户。向用户提供建议。 SUGGESTIONS(建议) 评估后决定是否应用。无需强制修复。 -
修复-重新验证循环(Critical/High问题必须执行):
当验证存在CRITICAL或HIGH问题时: 1. 编辑生成的文件以修复问题 2. 重新运行验证 3. 重复直到没有CRITICAL或HIGH问题 -
呈现给用户前需确保:
- 无CRITICAL问题
- 无HIGH问题
- MEDIUM问题已修复或已解释为何可接受
- LOW问题和建议已告知用户
-
呈现已验证的配置时:
- 明确说明验证状态
- 说明使用的验证路径(工具、脚本回退或手动回退)
- 列出所有剩余的MEDIUM/LOW问题并解释
- 包含模板/版本新鲜度说明
- 提供使用说明
- 提及所做的权衡
Critical/High问题的检查是严格且强制的,对于声称可用于生产环境的配置绝不能跳过。
Validation Pass Criteria
验证通过标准
Pipeline is READY to present when:
- ✅ Validation path executed (validator skill or script fallback)
- ✅ Syntax validation: PASSED
- ✅ Security scan: No CRITICAL or HIGH issues
- ✅ Best practices: Reviewed (warnings acceptable with explanation)
Pipeline is NOT READY when:
- ❌ Any syntax errors exist
- ❌ Any CRITICAL security issues exist
- ❌ Any HIGH security issues exist
- ❌ Job references are broken
- ❌ Only manual fallback was used and Critical/High risks cannot be ruled out
流水线可呈现给用户的条件:
- ✅ 已执行验证(验证工具或脚本回退)
- ✅ 语法验证:通过
- ✅ 安全扫描:无CRITICAL或HIGH问题
- ✅ 最佳实践:已评审(警告可接受但需解释)
流水线不可呈现的条件:
- ❌ 存在任何语法错误
- ❌ 存在任何CRITICAL安全问题
- ❌ 存在任何HIGH安全问题
- ❌ 任务引用损坏
- ❌ 仅使用手动回退且无法排除Critical/High风险
When to Skip Validation
何时可跳过验证
Only skip validation when:
- Generating partial code snippets (not complete files)
- Creating examples for documentation purposes
- User explicitly requests to skip validation
仅在以下情况可跳过验证:
- 生成部分代码片段(非完整文件)
- 为文档目的创建示例
- 用户明确要求跳过验证
Handling MEDIUM Severity Issues (REQUIRED OUTPUT)
处理MEDIUM严重程度问题(必须输出)
When the validator reports MEDIUM severity issues, you MUST either fix them OR explain why they're acceptable. This explanation is REQUIRED in your output.
Required format for MEDIUM issue handling:
undefined当验证器报告MEDIUM严重程度问题时,必须修复问题或解释为何可接受。此解释必须包含在输出中。
MEDIUM问题处理的必填格式:
undefinedValidation Issues Addressed
已处理的验证问题
MEDIUM Severity Issues
MEDIUM严重程度问题
| Issue | Status | Explanation |
|---|---|---|
| [Issue code] | Fixed/Acceptable | [Why it was fixed OR why it's acceptable] |
**Example MEDIUM issue explanations:**
| 问题 | 状态 | 解释 |
|---|---|---|
| [问题代码] | 已修复/可接受 | 为何修复或为何可接受 |
**MEDIUM问题解释示例:**
Validation Issues Addressed
已处理的验证问题
MEDIUM Severity Issues
MEDIUM严重程度问题
| Issue | Status | Explanation |
|---|---|---|
| Acceptable | Using |
| Acceptable | This pipeline installs well-known packages (pytest, flake8) from PyPI. Using |
| Acceptable | The |
**When to FIX vs ACCEPT:**
| Scenario | Action |
|----------|--------|
| Production/high-security environment | FIX the issue |
| Issue has simple fix with no downside | FIX the issue |
| Fix adds significant complexity | ACCEPT with explanation |
| Fix requires external changes (e.g., CI/CD variables) | ACCEPT with explanation |
| Issue is false positive for this context | ACCEPT with explanation || 问题 | 状态 | 解释 |
|---|---|---|
| 可接受 | 使用 |
| 可接受 | 此流水线从PyPI安装知名包(pytest、flake8)。使用 |
| 可接受 | |
undefinedReviewing Suggestions (REQUIRED OUTPUT)
评审建议(必须输出)
When the validator provides suggestions, you MUST briefly acknowledge them and explain whether they should be applied.
Required format:
undefined当验证器提供建议时,必须简要确认并说明是否应应用。
必填格式:
undefinedValidator Suggestions Review
验证器建议评审
| Suggestion | Recommendation | Reason |
|---|---|---|
| [suggestion] | Apply/Skip | [Why] |
**Example suggestions review:**
| 建议 | 推荐操作 | 原因 |
|---|---|---|
| [建议内容] | 应用/跳过 | 原因 |
**建议评审示例:**
Validator Suggestions Review
验证器建议评审
| Suggestion | Recommendation | Reason |
|---|---|---|
| Skip | Test jobs are deterministic and don't interact with external services. Retry would mask flaky tests rather than fail fast. |
| Apply if beneficial | Could be added if pytest supports sharding. Add |
| Skip | This job is manual and only runs on environment cleanup. DAG optimization wouldn't provide meaningful speedup. |
| Apply for production | Consider using |
| Skip | Rollback jobs don't deploy new versions, so a URL would be misleading. |
| Skip | Linting doesn't produce coverage data. This is a false positive. |
undefined| 建议 | 推荐操作 | 原因 |
|---|---|---|
| 跳过 | 测试任务是确定性的,不与外部服务交互。重试会掩盖不稳定的测试,而非快速失败。 |
| 若有益则应用 | 如果pytest支持分片则可添加。如果测试套件足够大,可添加 |
| 跳过 | 此任务是手动触发的,仅在环境清理时运行。DAG优化不会带来明显的速度提升。 |
| 生产环境建议应用 | 考虑使用 |
| 跳过 | 回退任务不部署新版本,因此URL会产生误导。 |
| 跳过 | 代码检查不会生成覆盖率数据。这是误报。 |
undefinedTemplate and Version Notes (REQUIRED OUTPUT)
模板和版本说明(必须输出)
After validation results, include a concise freshness note for templates and documentation assumptions.
Required format:
markdown
undefined验证结果后,需包含关于模板和文档假设的简洁新鲜度说明。
必填格式:
markdown
undefinedTemplate 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]
**Example:**
```markdown- 模板基础: [assets/templates/<file>.yml]
- 模板自定义范围: [与模板相比的修改内容]
- 版本/文档依据: [Context7、docs.gitlab.com或仅本地参考资源]
- 新鲜度说明: [检查的确切日期,或"无法进行外部查询"]
- 版本敏感假设: [若有]
**示例:**
```markdownTemplate 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 template path
Jobs/SAST.gitlab-ci.yml
undefined- 模板基础: assets/templates/docker-build.yml
- 模板自定义范围: 添加了单元测试阶段和环境特定的部署规则
- 版本/文档依据: docs.gitlab.com的include-template文档 + 本地参考资源
- 新鲜度说明: 2026-02-28验证了模板语法
- 版本敏感假设: 使用模板路径
Jobs/SAST.gitlab-ci.yml
undefinedUsage Instructions Template (REQUIRED OUTPUT)
使用说明模板(必须输出)
After presenting the validated pipeline, you MUST provide usage instructions. This is NOT optional.
Required format:
undefined呈现已验证的流水线后,必须提供使用说明。此步骤不可省略。
必填格式:
undefinedUsage Instructions
使用说明
Required CI/CD Variables
所需CI/CD变量
Configure these variables in Settings → CI/CD → Variables:
| Variable | Description | Masked | Protected |
|---|---|---|---|
| [VARIABLE_NAME] | [Description] | Yes/No | Yes/No |
在设置 → CI/CD → 变量中配置以下变量:
| 变量 | 描述 | 掩码化 | 受保护 |
|---|---|---|---|
| [VARIABLE_NAME] | [描述] | 是/否 | 是/否 |
Setup Steps
设置步骤
- [First setup step]
- [Second setup step] ...
- [第一个设置步骤]
- [第二个设置步骤] ...
Pipeline Behavior
流水线行为
- On push to : [What happens]
develop - On push to : [What happens]
main - On tag : [What happens]
vX.Y.Z
- 推送到分支时: [执行操作]
develop - 推送到分支时: [执行操作]
main - 打标签时: [执行操作]
vX.Y.Z
Customization
自定义
[Any customization notes]
**Example usage instructions:**
[任何自定义说明]
**使用说明示例:**
Usage Instructions
使用说明
Required CI/CD Variables
所需CI/CD变量
Configure these variables in Settings → CI/CD → Variables:
| Variable | Description | Masked | Protected |
|---|---|---|---|
| Kubernetes cluster context name | No | Yes |
| Staging namespace (default: staging) | No | No |
| Production namespace (default: production) | No | Yes |
Note: , , and are automatically provided by GitLab.
CI_REGISTRY_USERCI_REGISTRY_PASSWORDCI_REGISTRY在设置 → CI/CD → 变量中配置以下变量:
| 变量 | 描述 | 掩码化 | 受保护 |
|---|---|---|---|
| Kubernetes集群上下文名称 | 否 | 是 |
| 预发布环境命名空间(默认:staging) | 否 | 否 |
| 生产环境命名空间(默认:production) | 否 | 是 |
注意: 、和由GitLab自动提供。
CI_REGISTRY_USERCI_REGISTRY_PASSWORDCI_REGISTRYKubernetes Integration Setup
Kubernetes集成设置
- Enable Kubernetes integration in Settings → Infrastructure → Kubernetes clusters
- Add your cluster using the agent-based or certificate-based method
- Create namespaces for staging and production if they don't exist:
bash
kubectl create namespace staging kubectl create namespace production - Ensure deployment exists in the target namespaces before running the pipeline
- 启用Kubernetes集成 在设置 → 基础设施 → Kubernetes集群中
- 添加集群 使用基于Agent或基于证书的方式
- 创建命名空间 如果预发布和生产环境的命名空间不存在则创建:
bash
kubectl create namespace staging kubectl create namespace production - 确保部署存在 在运行流水线前,目标命名空间中需已有对应的deployment
Pipeline Behavior
流水线行为
- On push to : Runs tests → builds Docker image → deploys to staging automatically
develop - On push to : Runs tests → builds Docker image → manual deployment to production
main - On tag : Runs tests → builds Docker image → manual deployment to production
vX.Y.Z
- 推送到分支时: 运行测试 → 构建Docker镜像 → 自动部署到预发布环境
develop - 推送到分支时: 运行测试 → 构建Docker镜像 → 手动部署到生产环境
main - 打标签时: 运行测试 → 构建Docker镜像 → 手动部署到生产环境
vX.Y.Z
Customization
自定义
- Update variable to match your Kubernetes deployment name
APP_NAME - Modify environment URLs in and
deploy-stagingjobsdeploy-production - Add Helm deployment by uncommenting the Helm jobs in the template
undefined- 更新变量以匹配你的Kubernetes deployment名称
APP_NAME - 修改和
deploy-staging任务中的环境URLdeploy-production - 通过取消注释模板中的Helm任务来添加Helm部署
undefinedBest Practices to Enforce
需强制执行的最佳实践
Reference for comprehensive guidelines. Key principles:
references/best-practices.md参考获取全面指南。核心原则:
references/best-practices.mdMandatory Standards
强制标准
-
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
-
Performance:
- Implement caching for dependencies (ALWAYS for npm, pip, maven, etc.)
- Use keyword for DAG optimization (ALWAYS when jobs have dependencies)
needs - Set artifact expiration to avoid storage bloat (ALWAYS set )
expire_in - Use execution when applicable (only if test framework supports sharding)
parallel - Minimize unnecessary artifact passing (use in
artifacts: falsewhen not needed)needs
-
Reliability:
- Set explicit for ALL jobs (prevents hanging jobs, typically 10-30 minutes)
timeout- Even when using or
defaultfor timeout inheritance, add explicitextendsto each jobtimeout - This improves readability and avoids validator warnings about missing timeout
- Example: A job using should still have
.deploy-templateexplicitly settimeout: 15 minutes
- Even when using
- Add retry logic for flaky operations (network calls, external API interactions)
- Use appropriately for non-critical jobs (linting, optional scans)
allow_failure - Use for deployment jobs (prevents concurrent deployments)
resource_group - Add for test jobs (allows cancellation when new commits push)
interruptible: true
- Set explicit
-
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")
-
Configuration Organization:
- Use for reusable configuration (PREFERRED over YAML anchors for GitLab CI)
extends - Use for modular pipeline files (organize large pipelines into multiple files)
include - Use instead of deprecated only/except (ALWAYS)
rules - Define settings for common configurations (image, timeout, cache, tags)
default - Use YAML anchors only when necessary for complex repeated structures within a single file
- Note: is preferred because it provides better visualization in GitLab UI
extends
- Note:
- Use
-
Error Handling:
- Set appropriate timeout values (ALWAYS - prevents hanging jobs)
- Configure retry behavior for flaky operations (network calls, external APIs)
- Use for non-blocking jobs (linting, optional scans)
allow_failure: true - Add cleanup steps with when needed (e.g., stopping test containers, cleanup)
after_script - Implement notification mechanisms when required (e.g., Slack integration for deployment failures)
-
安全优先:
- 固定Docker镜像到特定版本(不使用:latest)
- 对敏感信息使用掩码化变量($CI_REGISTRY_PASSWORD应掩码化)
- 绝不在日志中暴露敏感信息
- 验证输入并清理变量
- 对敏感环境使用受保护变量
-
性能:
- 为依赖项实现缓存(npm、pip、maven等必须启用)
- 使用关键字进行DAG优化(任务有依赖时必须使用)
needs - 设置产物过期时间以避免存储膨胀(必须设置)
expire_in - 适当情况下使用执行(仅当测试框架支持分片时)
parallel - 最小化不必要的产物传递(不需要时在中使用
needs)artifacts: false
-
可靠性:
- 为所有任务设置明确的(防止任务挂起,通常为10-30分钟)
timeout- 即使使用或
default继承超时时间,仍需为每个任务添加明确的extendstimeout - 这提升了可读性并避免验证器关于缺失超时的警告
- 示例:使用的任务仍应明确设置
.deploy-templatetimeout: 15 minutes
- 即使使用
- 为不稳定操作(网络调用、外部API交互)添加重试逻辑
- 对非关键任务(代码检查、可选扫描)适当使用
allow_failure - 为部署任务使用(防止并发部署)
resource_group - 为测试任务添加(新提交推送时可取消任务)
interruptible: true
- 为所有任务设置明确的
-
命名:
- 任务名称:描述性、短横线分隔(例如:"build-application"、"test-unit")
- 阶段名称:简短、清晰(例如:"build"、"test"、"deploy")
- 变量名称:环境变量使用大写下划线分隔(UPPER_SNAKE_CASE)
- 环境名称:小写(例如:"production"、"staging")
-
配置组织:
- 使用实现可复用配置(GitLab CI中优先于YAML锚点)
extends - 使用组织模块化流水线文件(将大型流水线拆分为多个文件)
include - 使用替代已弃用的only/except(必须)
rules - 为通用配置(镜像、超时、缓存、标签)定义设置
default - 仅在必要时使用YAML锚点处理单个文件中的复杂重复结构
- 注意:更受推荐,因为它在GitLab UI中提供更好的可视化效果
extends
- 注意:
- 使用
-
错误处理:
- 设置适当的超时值(必须 - 防止任务挂起)
- 为不稳定操作(网络调用、外部API)配置重试行为
- 对非阻塞任务(代码检查、可选扫描)使用
allow_failure: true - 必要时使用添加清理步骤(例如:停止测试容器、清理资源)
after_script - 必要时实现通知机制(例如:部署失败时的Slack集成)
Resources
资源
References (Tiered Loading)
参考资源(分层加载)
-
(Tier 1: required for all) - Comprehensive GitLab CI/CD best practices
references/best-practices.md- Security patterns, performance optimization
- Pipeline design, configuration organization
- Common patterns and anti-patterns
- Use this: When implementing any GitLab CI/CD resource
-
(Tier 1: required for all) - Frequently used pipeline patterns
references/common-patterns.md- 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
-
(Tier 2: required for Full mode) - GitLab CI/CD YAML syntax reference
references/gitlab-ci-reference.md- Complete keyword reference
- Job configuration options
- Rules and conditional execution
- Variables and environments
- Use this: For syntax and keyword details
-
(Tier 2: required for Full mode) - Security best practices
references/security-guidelines.md- Secrets management
- Image security
- Script security
- Artifact security
- Use this: For security-sensitive configurations
-
(第1层级:所有场景必填)- 全面的GitLab CI/CD最佳实践
references/best-practices.md- 安全模式、性能优化
- 流水线设计、配置组织
- 通用模式和反模式
- 使用时机: 实现任何GitLab CI/CD资源时
-
(第1层级:所有场景必填)- 常用流水线模式
references/common-patterns.md- 基础CI流水线模式
- Docker构建和推送模式
- 部署模式(K8s、云平台)
- 多项目和父子流水线模式
- 使用时机: 选择使用哪种模式时
-
(第2层级:完整模式必填)- GitLab CI/CD YAML语法参考
references/gitlab-ci-reference.md- 完整关键字参考
- 任务配置选项
- 规则和条件执行
- 变量和环境
- 使用时机: 获取语法和关键字细节时
-
(第2层级:完整模式必填)- 安全最佳实践
references/security-guidelines.md- 敏感信息管理
- 镜像安全
- 脚本安全
- 产物安全
- 使用时机: 处理安全敏感配置时
Assets (Templates to Customize)
资源文件(可自定义的模板)
- - Complete basic pipeline template
assets/templates/basic-pipeline.yml - - Docker build pipeline template
assets/templates/docker-build.yml - - Kubernetes deployment template
assets/templates/kubernetes-deploy.yml - - Multi-project orchestration template
assets/templates/multi-project.yml
How to use templates:
- Copy the relevant template structure
- Replace all with actual values
[PLACEHOLDERS] - Customize logic based on user requirements
- Remove unnecessary sections
- Validate the result
- - 完整的基础流水线模板
assets/templates/basic-pipeline.yml - - Docker构建流水线模板
assets/templates/docker-build.yml - - Kubernetes部署模板
assets/templates/kubernetes-deploy.yml - - 多项目编排模板
assets/templates/multi-project.yml
模板使用方法:
- 复制相关模板结构
- 将所有替换为实际值
[PLACEHOLDERS] - 根据用户需求自定义逻辑
- 删除不必要的部分
- 验证结果
Typical Workflow Example
典型工作流示例
User request: "Create a CI/CD pipeline for a Node.js app with testing and Docker deployment"
Process:
-
✅ Understand requirements:
- Node.js application
- Run tests (unit, lint)
- Build Docker image
- Deploy to container registry
- Trigger on push and merge requests
-
✅ Reference resources:
- Check for pipeline structure
references/best-practices.md - Check for Node.js + Docker pattern
references/common-patterns.md - Use as base
assets/templates/docker-build.yml
- Check
-
✅ 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
-
✅ Validate:
- Invoke skill
devops-skills:gitlab-ci-validator - Fix any reported issues
- Re-validate if needed
- Invoke
-
✅ Present to user:
- Show validated pipeline
- Explain key sections
- Provide usage instructions
- Mention successful validation
用户请求: "为Node.js应用创建包含测试和Docker部署的CI/CD流水线"
流程:
-
✅ 理解需求:
- Node.js应用
- 运行测试(单元测试、代码检查)
- 构建Docker镜像
- 部署到容器仓库
- 推送和合并请求时触发
-
✅ 参考资源:
- 查看获取流水线结构
references/best-practices.md - 查看获取Node.js + Docker模式
references/common-patterns.md - 使用作为基础
assets/templates/docker-build.yml
- 查看
-
✅ 生成流水线:
- 定义阶段(build、test、dockerize、deploy)
- 创建带缓存的构建任务
- 创建带needs优化的测试任务(单元、代码检查)
- 创建Docker构建任务
- 添加正确的产物管理
- 固定Docker镜像版本
- 包含正确的敏感信息处理
-
✅ 验证:
- 调用工具
devops-skills:gitlab-ci-validator - 修复任何报告的问题
- 必要时重新验证
- 调用
-
✅ 呈现给用户:
- 展示已验证的流水线
- 解释关键部分
- 提供使用说明
- 提及验证成功
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: manualyaml
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: manualDAG Pipeline with Needs
带Needs的DAG流水线
yaml
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 deployyaml
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 deployConditional Execution with Rules
带Rules的条件执行
yaml
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: neveryaml
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: neverMatrix Parallel Jobs
矩阵并行任务
yaml
test:
parallel:
matrix:
- NODE_VERSION: ['18', '20', '22']
OS: ['ubuntu', 'alpine']
image: node:${NODE_VERSION}-${OS}
script:
- npm testyaml
test:
parallel:
matrix:
- NODE_VERSION: ['18', '20', '22']
OS: ['ubuntu', 'alpine']
image: node:${NODE_VERSION}-${OS}
script:
- npm testError Messages and Troubleshooting
错误信息和故障排除
If devops-skills:gitlab-ci-validator reports errors:
若devops-skills:gitlab-ci-validator报告错误:
- Syntax errors: Fix YAML formatting, indentation, or structure
- Job reference errors: Ensure referenced jobs exist in needs/dependencies
- Stage errors: Verify all job stages are defined in stages list
- Rule errors: Check rules syntax and variable references
- Security warnings: Address hardcoded secrets and image pinning
- 语法错误: 修复YAML格式、缩进或结构
- 任务引用错误: 确保needs/依赖中引用的任务存在
- 阶段错误: 验证所有任务的阶段已在stages列表中定义
- 规则错误: 检查rules语法和变量引用
- 安全警告: 修复硬编码敏感信息和镜像固定问题
If GitLab documentation is not found:
若未找到GitLab文档:
- Try Context7 first: ->
mcp__context7__resolve-library-idmcp__context7__query-docs - If needed, run scoped to
web.search_querydocs.gitlab.com - Open specific pages with and extract only required syntax/variables
web.open - If offline, continue with local references and add version-assumption notes
- 优先尝试Context7:->
mcp__context7__resolve-library-idmcp__context7__query-docs - 必要时运行并限定在
web.search_querydocs.gitlab.com - 使用打开特定页面并仅提取所需的语法/变量
web.open - 离线时,继续使用本地参考资源并添加版本假设说明
PRE-DELIVERY CHECKLIST
交付前检查清单
MANDATORY: Before presenting ANY generated pipeline to the user, verify ALL items:
必须: 在向用户呈现任何生成的流水线前,验证所有项:
Mode and References
模式和参考资源
- Complexity mode selected (,
Targeted, orLightweight)Full - For Targeted mode: only directly relevant files/references loaded
- For Lightweight/Full modes: read before generating
references/best-practices.md - For Lightweight/Full modes: read before generating
references/common-patterns.md - For Lightweight/Full modes: read appropriate template from for the pipeline type
assets/templates/ - For Full mode: read
references/gitlab-ci-reference.md - For Full mode: read
references/security-guidelines.md - Output explicit confirmation statement for Lightweight/Full modes
- 已选择复杂度模式(、
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模式
Generation Standards Applied
生成标准已应用
- All Docker images pinned to specific versions (no )
:latest - All jobs have explicit (10-30 minutes typically)
timeout - block includes
defaultif definedtimeout - Hidden templates () include
.template-nametimeout - Caching configured for dependency installation
- keyword used for DAG optimization where appropriate
needs - used (not deprecated
rules/only)except - configured for deployment jobs
resource_group - Artifacts have set
expire_in - Secrets use masked CI/CD variables (not hardcoded)
- 所有Docker镜像已固定到特定版本(未使用)
:latest - 所有任务都有明确的(通常10-30分钟)
timeout - 块中若定义了则包含
defaulttimeout - 隐藏模板()包含
.template-nametimeout - 已为依赖项安装配置缓存
- 适当情况下使用关键字进行DAG优化
needs - 使用了(未使用已弃用的
rules/only)except - 已为部署任务配置
resource_group - 产物已设置
expire_in - 敏感信息使用掩码化CI/CD变量(未硬编码)
Validation Completed
验证已完成
- Validation executed via or script fallback
devops-skills:gitlab-ci-validator - Zero CRITICAL issues
- Zero HIGH issues
- MEDIUM issues addressed (fixed OR explained in output using required format)
- LOW issues acknowledged (listed in output)
- Suggestions reviewed (using required format)
- Re-validated after any fixes
- If only manual fallback was available: output marked as not fully verified
- 已通过或脚本回退执行验证
devops-skills:gitlab-ci-validator - 无CRITICAL问题
- 无HIGH问题
- MEDIUM问题已处理(已修复或在输出中使用必填格式解释)
- LOW问题已告知(已在输出中列出)
- 建议已评审(使用必填格式)
- 修复后已重新验证
- 若仅使用了手动回退:输出已标记为未完全验证
Presentation Ready
已准备好呈现
- Validation status stated clearly
- Validation path stated clearly (skill, script fallback, or manual fallback)
- MEDIUM/LOW issues explained (with table format)
- Suggestions review provided (with table format)
- Template and version notes provided (with required format)
- Usage instructions provided (with required sections)
- Key sections explained
If any checkbox is unchecked, DO NOT present the pipeline. Complete the missing steps first.
- 已明确说明验证状态
- 已明确说明验证路径(工具、脚本回退或手动回退)
- 已解释MEDIUM/LOW问题(使用表格格式)
- 已提供建议评审(使用表格格式)
- 已提供模板和版本说明(使用必填格式)
- 已提供使用说明(包含必填部分)
- 关键部分已解释
若任何复选框未勾选,不得呈现流水线。先完成缺失的步骤。
Required Output Sections
必填输出部分
Use the smallest valid output profile for the selected mode.
Full mode (complete/complex pipeline):
- Reference Analysis Complete (from Step 3)
- Generated Pipeline (the content)
.gitlab-ci.yml - Validation Results Summary (pass/fail status)
- Validation Issues Addressed (MEDIUM issues table)
- Validator Suggestions Review (suggestions table)
- Template and Version Notes (template base + freshness/version assumptions)
- Usage Instructions (variables, setup, behavior)
Lightweight mode (complete/simple pipeline):
- Reference Analysis Complete (Lightweight)
- Generated Pipeline
- Validation Results Summary
- Template and Version Notes
- Usage Instructions
- Add Validation Issues Addressed only when MEDIUM issues exist.
- Add Validator Suggestions Review only when suggestions are present.
Targeted mode (review/Q&A/snippet/focused fix):
- Provide only the directly requested artifact/answer and a concise rationale.
- Include validation/fallback disclosure if validation was not run.
- Do not force full pipeline-generation sections.
根据所选模式使用最小的有效输出模板。
Full模式(完整/复杂流水线):
- 参考分析完成(来自步骤3)
- 生成的流水线(内容)
.gitlab-ci.yml - 验证结果摘要(通过/失败状态)
- 已处理的验证问题(MEDIUM问题表格)
- 验证器建议评审(建议表格)
- 模板和版本说明(模板基础 + 新鲜度/版本假设)
- 使用说明(变量、设置、行为)
Lightweight模式(完整/简单流水线):
- 参考分析完成(轻量模式)
- 生成的流水线
- 验证结果摘要
- 模板和版本说明
- 使用说明
- 仅当存在MEDIUM问题时添加已处理的验证问题。
- 仅当存在建议时添加验证器建议评审。
Targeted模式(评审/问答/代码片段/针对性修复):
- 仅提供直接请求的产物/答案和简洁的理由。
- 若未执行验证,包含验证/回退说明。
- 不得强制添加完整流水线生成的部分。
Done Criteria
完成标准
This skill execution is done when:
- Simple requests use Lightweight mode without unnecessary Tier 2 loading.
- Complex requests use Full mode with Tier 2 references and complete confirmation.
- Validation enforces strict Critical/High gates before production-ready claims.
- Output includes template/version freshness notes plus usage instructions.
- Any fallback path is explicit and does not hide verification gaps.
当满足以下条件时,本工具执行完成:
- 简单请求使用Lightweight模式,无需加载不必要的第2层级资源。
- 复杂请求使用Full模式,加载第2层级参考资源并完成完整确认。
- 验证严格执行Critical/High检查,之后才声称配置可用于生产环境。
- 输出包含模板/版本新鲜度说明和使用说明。
- 任何回退路径都明确说明,不隐藏验证缺口。
Summary
总结
Always follow this sequence when generating GitLab CI/CD pipelines:
- Classify Complexity - choose ,
Targeted, orLightweightmode.Full - Load References - use tiered loading:
- For mode, load only directly relevant files.
Targeted - For modes, load:
Lightweight/Fullreferences/best-practices.mdreferences/common-patterns.md- Plus the appropriate template from
assets/templates/
- For mode, also load:
Fullreferences/gitlab-ci-reference.mdreferences/security-guidelines.md
- For
- Confirm - Output targeted response or Lightweight/Full reference analysis as required by mode.
- Generate - Use templates and follow standards (security, caching, naming, explicit timeout on ALL jobs).
- Lookup Docs When Needed - Context7 first, then /
web.search_query, with offline fallback notes when constrained.web.open - Validate - Use , script fallback if needed.
devops-skills:gitlab-ci-validator - Fix - Resolve all Critical/High issues, address Medium issues.
- Verify Checklist - Confirm all pre-delivery checklist items.
- Present - Deliver output with validation summary, template/version notes, and usage instructions.
Generate GitLab CI/CD pipelines that are:
- ✅ Secure with pinned images and proper secrets handling
- ✅ Following current best practices and conventions
- ✅ Using proper configuration organization (extends, includes)
- ✅ Optimized for performance (caching, needs, DAG)
- ✅ Properly documented with usage instructions
- ✅ Validated with zero Critical/High issues
- ✅ Production-ready and maintainable
生成GitLab CI/CD流水线时始终遵循以下顺序:
- 分类复杂度 - 选择、
Targeted或Lightweight模式。Full - 加载参考资源 - 分层加载:
- 模式:仅加载直接相关的文件。
Targeted - 模式:加载:
Lightweight/Fullreferences/best-practices.mdreferences/common-patterns.md- 对应流水线类型的模板
assets/templates/
- 模式:额外加载:
Fullreferences/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问题
- ✅ 可用于生产环境且易于维护