mcpField
K
k8s-yaml-validator

k8s-yaml-validator

github.com/akin-ozer测试与质量329679 次安装16 周前更新
代码仓库

关于 k8s-yaml-validator

k8s-yaml-validator 是面向 Kubernetes 清单的只读验证技能,适合部署前检查和错误排查。它涵盖 YAML lint、Schema 验证、可用时的集群 dry-run,以及 CRD 文档查询,并输出问题报告和修复建议。

主要功能

  1. 01统计 YAML 文档数量
  2. 02检查 YAML 语法与格式
  3. 03检测 CRD 并查询文档
  4. 04验证 Kubernetes Schema
  5. 05执行集群 dry-run
  6. 06生成只读问题报告

适用场景

  1. 01应用清单前进行验证
  2. 02排查多文档 YAML 错误
  3. 03核对 CRD Schema 问题
  4. 04检查集群准入策略错误

MCP 相关

可优先使用 Context7 MCP 查询检测到的 CRD 文档;若查询失败或信息不足,则使用网页搜索。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/akin-ozer/cc-devops-skills --skill k8s-yaml-validator

安装后在 Claude Code 中输入/k8s-yaml-validator确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
.yamllint
references/
k8s_best_practices.md
validation_workflow.md
scripts/
count_yaml_documents.py
detect_crd_wrapper.sh
detect_crd.py
setup_tools.sh
test_count_yaml_documents.py
test/
certificate-crd-test.yaml
comprehensive-test.yaml
deployment-test.yaml
document-counter-edge-cases.yaml
schema-errors-test.yaml

详细介绍

Kubernetes YAML 验证器

概述

此技能提供全面的 Kubernetes YAML 资源验证工作流,结合语法 lint、架构验证、集群 dry-run 测试和智能 CRD 文档查询。在将任何 Kubernetes 清单应用到集群之前,都可以放心地对其进行验证。

重要:这是一个仅生成报告的验证工具。 不要修改文件,不要使用 Edit 工具,也不要使用 AskUserQuestion 提供修复方案。生成一份全面的验证报告,并通过修复前后的代码块展示建议,然后让用户决定接下来怎么做。

触发语句

当提示内容类似以下情况时,使用此技能:

  • “部署前验证此 Kubernetes YAML。”
  • “Lint 这些清单,并报告其中的问题。”
  • “检查此 CRD 清单并解释架构问题。”
  • “对此清单运行 dry-run 检查。”
  • “找出这个多文档 YAML 中具体到行的错误。”

何时使用此技能

在以下情况下调用此技能:

  • 在将 Kubernetes YAML 文件应用到集群之前进行验证
  • 调试 YAML 语法或格式错误
  • 使用自定义资源定义(CRD)并需要查阅文档
  • 执行 dry-run 测试以捕获准入控制器错误
  • 确保 YAML 符合 Kubernetes 最佳实践
  • 了解清单中存在哪些验证错误(仅生成报告,由用户手动修复)
  • 用户要求“验证”“lint”“检查”或“测试”Kubernetes YAML 文件

只读边界(强制)

此技能严格限定为仅生成报告:

  • 不要修改任何用户文件。
  • 不要运行 Edit 来修复问题。
  • 不要询问是否可以应用修复。
  • 应在报告中提供修复前后的代码片段作为建议。

确定性路径设置

使用明确路径运行,以确保命令可重复:

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
SKILL_DIR="$REPO_ROOT/devops-skills-plugin/skills/k8s-yaml-validator"
TARGET_FILE="$REPO_ROOT/<relative/path/to/file.yaml>"

路径检查:

  • 如果 REPO_ROOT 为空,则停止并询问仓库根目录。
  • 如果 SKILL_DIR 不存在,则停止并报告路径不匹配。
  • 如果 TARGET_FILE 不存在,则停止并询问正确的文件。

验证工作流

按顺序遵循此验证工作流。每个阶段都会捕获不同类型的问题:

阶段 0:验证前设置(确定性资源计数)

运行验证器之前,使用随附脚本统计文档数量:

python3 "$SKILL_DIR/scripts/count_yaml_documents.py" "$TARGET_FILE"

预期输出(示例):

{
  "file": ".../manifests.yaml",
  "documents": 3,
  "separators": 2
}

门槛规则:

  • 如果 documents >= 3,则在阶段 1 之前加载 references/validation_workflow.md。
  • 最终报告摘要中始终包含文档数量。
  • 如果无法使用 python3,则使用以下备用方案:
awk 'BEGIN{d=0;seen=0} /^[[:space:]]*---[[:space:]]*$/ {if(seen){d++;seen=0}; next} /^[[:space:]]*#/ {next} NF{seen=1} END{if(seen)d++; print d}' "$TARGET_FILE"

并在报告中将计数标记为 estimated。

阶段 1:工具检查

开始验证之前,确认所需工具已安装:

bash "$SKILL_DIR/scripts/setup_tools.sh"

所需工具:

  • yamllint:YAML 语法和风格 lint
  • kubeconform:支持 CRD 的 Kubernetes 架构验证
  • kubectl:集群 dry-run 测试(可选,但建议使用)

如果缺少工具,则显示脚本输出中的安装指南,并继续使用可用工具。请在报告中记录缺失的工具和跳过的阶段。

阶段 2:YAML 语法验证

使用 yamllint 验证 YAML 语法和格式:

yamllint -c "$SKILL_DIR/assets/.yamllint" "$TARGET_FILE"

常见问题:

  • 缩进错误(制表符与空格混用)
  • 尾随空格
  • 行长度违规
  • 语法错误
  • 重复键

报告方式:

  • 报告所有语法问题,并注明文件和行号
  • 对于可修复的问题,通过修复前后的代码块展示建议
  • 继续进行下一验证阶段,先收集所有问题,再生成报告
阶段 3:CRD 检测和文档查询

在进行架构验证之前,检测 YAML 是否包含自定义资源定义(CRD):

bash "$SKILL_DIR/scripts/detect_crd_wrapper.sh" "$TARGET_FILE"

如果 PyYAML 不可用,包装脚本会通过创建临时虚拟环境自动处理 Python 依赖。

弹性解析: 脚本能够应对单个文档中的语法错误。如果多文档 YAML 文件中既有有效文档,也有无效文档,脚本将:

  • 解析有效文档并检测其中的 CRD
  • 报告无效文档的错误,但继续处理
  • 这与 kubeconform 的行为一致:即使 1/3 的资源存在语法错误,仍会验证 2/3 的资源

脚本会输出包含资源信息和解析状态的 JSON:

{
  "resources": [
    {
      "kind": "Certificate",
      "apiVersion": "cert-manager.io/v1",
      "group": "cert-manager.io",
      "version": "v1",
      "isCRD": true,
      "name": "example-cert"
    }
  ],
  "parseErrors": [
    {
      "document": 1,
      "start_line": 2,
      "error_line": 6,
      "error": "mapping values are not allowed in this context"
    }
  ],
  "summary": {
    "totalDocuments": 3,
    "parsedSuccessfully": 2,
    "parseErrors": 1,
    "crdsDetected": 1
  }
}

针对每个检测到的 CRD:

  1. 优先尝试 Context7 MCP:

    • 解析库:
      • 工具:mcp__context7__resolve-library-id
      • libraryName:CRD 项目名称(例如,cert-manager.io 对应 cert-manager)
    • 查询文档:
      • 工具:mcp__context7__query-docs
      • libraryId:上一步解析得到的库 ID
      • query:包含 CRD 的种类、组和版本(例如,Certificate cert-manager.io v1 required fields in spec)
  2. 如果 Context7 失败或返回的信息不足,则回退到 web.search_query:

    Search query pattern:
    "<kind>" "<group>" kubernetes CRD "<version>" documentation spec
    
    Example:
    "Certificate" "cert-manager.io" kubernetes CRD "v1" documentation spec
    
  3. 提取关键信息:

    • spec 中的必填字段
    • 字段类型和验证规则
    • 文档中的示例
    • 特定版本的变更或弃用信息

通过 kubeconform 进行二次 CRD 检测: 如果 detect_crd_wrapper.sh 无法识别 CRD(例如,所有文档都存在语法错误),但 kubeconform 仍然验证了 CRD 资源,则仍需查询该 CRD 的文档。解析 kubeconform 输出以识别已验证的 CRD,并通过 Context7/web.search_query 查询文档。

这很重要的原因: CRD 使用的自定义架构在标准 Kubernetes 验证工具中不可用。了解 CRD 的 spec 要求可以避免验证错误,并确保资源配置正确。

阶段 4:架构验证

使用 kubeconform 根据 Kubernetes 架构进行验证:

kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -strict \
  -ignore-missing-schemas \
  -summary \
  -verbose \
  "$TARGET_FILE"

选项说明:

  • -strict:拒绝未知字段(生产环境推荐,可捕获拼写错误)
  • -ignore-missing-schemas:跳过对没有可用架构的 CRD 的验证
  • -kubernetes-version 1.30.0:根据指定的 K8s 版本进行验证

常见问题:

  • 无效的 apiVersion 或 kind
  • 缺少必填字段
  • 字段类型错误
  • 无效的枚举值
  • 未知字段(使用 -strict 时)

对于 CRD: 如果 kubeconform 报告“no schema found”,这是预期行为。使用阶段 3 中的文档手动验证 spec 字段。

kubeconform 的行号行为——两种不同情况:

kubeconform 不会报告相对于文件的绝对行号。你必须进行转换:

  1. 解析错误(例如 error converting YAML to JSON: yaml: line N):

    • N 是相对于文档的行号(文档内容中的第 N 行)。
    • 转换为文件绝对行号:file_line = doc_start_line + N - 1
    • doc_start_line 来自 detect_crd_wrapper.sh 输出中的 start_line 字段。
    • 示例:文档从文件第 4 行开始,kubeconform 报告 yaml: line 5 → 文件绝对行号 = 4 + 5 − 1 = 第 8 行(与 yamllint 输出一致)。
  2. 架构验证错误(例如 got string, want integer):

    • kubeconform 只报告 JSON 路径,不提供行号。
    • 示例:at '/spec/template/spec/containers/0/ports/0/containerPort': got string, want integer
    • 查找行号:在相关文档部分中搜索 YAML 文件的字段名称(例如 containerPort),并使用周边上下文中的文件绝对行号。

在验证报告中始终使用文件绝对行号,即使需要从 kubeconform 输出的文档相对行号进行转换。

阶段 5:集群试运行(如可用)

重要:始终先尝试服务端试运行。 服务端验证能发现比客户端验证更多的问题,因为它会经过准入控制器和 Webhook。

决策树:

1. Try server-side dry-run first:
   kubectl apply --dry-run=server -f "$TARGET_FILE"

   └─ If SUCCESS → Use results, continue to Stage 6

   └─ If FAILS with connection error (e.g., "connection refused",
      "unable to connect", "no configuration"):
      │
      ├─ 2. Attempt client-side dry-run (parse-only fallback):
      │     kubectl apply --dry-run=client --validate=false -f "$TARGET_FILE"
      │
      │     ├─ If SUCCESS:
      │     │    Document in report: "Server-side validation skipped (no cluster access); client fallback ran in parse-only mode"
      │     │
      │     └─ If FAILS with discovery/openapi error (e.g., "unable to recognize",
      │        "failed to download openapi", "couldn't get current server API group list"):
      │        Document in report: "Dry-run skipped (cluster discovery unavailable)"
      │        Continue to Stage 6
      │
      └─ If FAILS with validation error (e.g., "admission webhook denied",
         "resource quota exceeded", "invalid value"):
         └─ Record the error, continue to Stage 6

   └─ If FAILS with parse error (e.g., "error converting YAML to JSON",
      "yaml: line X: mapping values are not allowed"):
      └─ Record the error, skip client-side dry-run (same error will occur)
         Document in report: "Dry-run blocked by YAML syntax errors - fix syntax first"
         Continue to Stage 6

注意: 前序阶段(yamllint、kubeconform)中的解析错误也会导致试运行失败。解析错误时,不要尝试将客户端试运行作为回退方案——它会产生相同的错误。必须先修复解析错误,才能继续进行试运行验证。

服务端试运行可发现:

  • 准入控制器拒绝
  • 策略违规(PSP、OPA、Kyverno 等)
  • 资源配额违规
  • 缺少命名空间
  • ConfigMap/Secret 引用无效
  • Webhook 验证

使用 --validate=false 的客户端试运行可发现(回退方案,命令成功时):

  • YAML/JSON 转换和请求构造问题
  • kubectl 是否能在客户端模式下处理并提交清单格式
  • 注意: --validate=false 会禁用架构、类型和必填字段验证,仍然无法发现准入控制器或策略问题。

在报告中注明使用的模式:

  • 如果为服务端:「已执行完整集群验证」
  • 如果使用 --validate=false 的客户端模式:「有限的纯解析验证(无集群访问权限)——未检查架构和准入策略」
  • 如果跳过:「已跳过试运行——kubectl 不可用」
  • 如果尝试客户端回退后跳过:「已跳过试运行(集群发现不可用)」

对于现有资源的更新:

kubectl diff -f "$TARGET_FILE"

这会显示将发生的更改,帮助发现意外修改。

第 6 阶段:生成详细验证报告(仅报告)

完成所有验证阶段后,生成一份全面的报告。此阶段仅用于报告。

绝对不要执行以下操作:

  • 不要使用 Edit 工具修改文件
  • 不要使用 AskUserQuestion 提出修复问题
  • 不要提示用户询问是否要应用修复
  • 不要修改任何 YAML 文件

务必执行以下操作:

  • 生成一份全面的验证报告
  • 仅以建议的形式展示修改前后的代码块
  • 让用户在查看报告后自行决定如何处理
  • 以供用户手动执行的“后续步骤”结尾
  1. 以表格形式总结所有阶段发现的问题:

    | Severity | Stage | Location | Issue | Suggested Fix |
    |----------|-------|----------|-------|---------------|
    | Error | Syntax | file.yaml:5 | Indentation error | Use 2 spaces |
    | Error | Schema | file.yaml:21 | Wrong type | Change to integer |
    | Warning | Best Practice | file.yaml:30 | Missing labels | Add app label |
    
  2. 按严重程度分类:

    • 错误(必须修复):语法错误、缺少必填字段、dry-run 失败
    • 警告(应该修复):风格问题、违反最佳实践
    • 信息(可选):改进建议
  3. 为每个问题展示修改前后的代码块:

    对于每个问题,展示明确的修改前/修改后 YAML 片段,以说明建议的修复方案:

    **Issue 1: deployment.yaml:21 - Wrong field type (Error)**
    
    Current:
    ```yaml
            - containerPort: "80"
    

    建议的修复:

            - containerPort: 80
    

    原因: containerPort 必须是整数,而不是字符串。Kubernetes 会拒绝字符串值。 参考:请参阅 k8s_best_practices.md 中的“无效值”部分。

  4. Provide validation summary:

    ## 验证报告摘要
    
    文件:deployment.yaml
    已分析的资源:3(Deployment、Service、Certificate)
    
    | 阶段 | 状态 | 发现的问题 |
    |-------|--------------|------------|
    | YAML 语法 | ❌ 失败 | 2 个错误 |
    | CRD 检测 | ✅ 通过 | 检测到 1 个 CRD(Certificate) |
    | 架构验证 | ❌ 失败 | 1 个错误 |
    | Dry-Run | ❌ 失败 | 1 个错误 |
    
    问题总数:4 个错误、2 个警告
    
    ## 详细结果
    
    [按上文所示,为每个问题列出修改前后的代码块]
    
    ## 后续步骤
    
    1. 修复上面列出的 4 个错误(否则部署将失败)
    2. 考虑按照最佳实践处理 2 个警告
    3. 修复后重新运行验证,确认问题已解决
    
  5. Do NOT modify files - this is a reporting tool only

    • Present all findings clearly
    • Let the user decide which fixes to apply
    • User can request fixes after reviewing the report

Objective Stage Gates (Repeatable)

Use this table to keep stage decisions deterministic:

StageRequiredCommandPass/Fail CriteriaFallback
0 Resource CountYespython3 "$SKILL_DIR/scripts/count_yaml_documents.py" "$TARGET_FILE"Pass when count output is produced and documents is recorded.Use AWK estimator and mark estimated.
1 Tool CheckYesbash "$SKILL_DIR/scripts/setup_tools.sh"Pass when command runs and tool availability is known.Continue with available tools and log skips.
2 YAML SyntaxIf yamllint availableyamllint -c "$SKILL_DIR/assets/.yamllint" "$TARGET_FILE"Pass on exit code 0; fail on lint errors.Skip with explicit reason if missing binary.
3 CRD DetectionIf python3 availablebash "$SKILL_DIR/scripts/detect_crd_wrapper.sh" "$TARGET_FILE"Pass when JSON output includes summary.Skip CRD extraction and rely on kubeconform clues.
4 SchemaIf kubeconform availablekubeconform command from Stage 4Pass when kubeconform reports valid resources.Skip and record as coverage gap if missing binary.
5 Dry-RunIf kubectl availablekubectl apply --dry-run=server -f "$TARGET_FILE"Pass on successful server dry-run.Attempt parse-only client fallback with --dry-run=client --validate=false; if discovery still fails, mark stage skipped.
6 ReportYesReport generationPass when summary + per-issue snippets + next steps are provided.No fallback; this stage is mandatory.

Fallback Matrix

ConstraintActionReport Language
python3 unavailableSkip count_yaml_documents.py and CRD parser scripts. Use AWK count only.Python runtime unavailable; CRD parser skipped, resource count is estimated.
yamllint unavailableSkip Stage 2; continue with schema/dry-run stages if available.YAML lint skipped because yamllint is not installed.
kubeconform unavailableSkip Stage 4; run lint and dry-run only.Schema validation skipped because kubeconform is not installed.
kubectl unavailableSkip Stage 5 entirely.Dry-run skipped because kubectl is not installed.
No cluster connectivityRun server-side first, then attempt parse-only client fallback with --dry-run=client --validate=false; if it still fails, skip dry-run and continue.Server-side dry-run unavailable due cluster access; parse-only client-side dry-run attempted (schema checks disabled).
Client dry-run still requires discoveryTreat dry-run as unavailable and rely on lint + schema stages.Dry-run skipped (cluster discovery unavailable); lint and schema results used.
External docs unavailableContinue local validation and state documentation gap.CRD documentation lookup deferred due tooling/network limitation.

Best Practices Reference

For detailed Kubernetes YAML best practices, load the reference:

Read "$SKILL_DIR/references/k8s_best_practices.md"

This reference includes:

  • Metadata and label conventions
  • Resource limits and requests
  • Security context guidelines
  • Probe configurations
  • Common validation issues and fixes

When to load (ALWAYS load in these cases):

  • Schema validation fails with type errors (e.g., string vs integer, invalid values)
  • Schema validation reports missing required fields
  • kubeconform reports invalid field values or unknown fields
  • Dry-run fails with validation errors related to resources, probes, or security
  • When explaining why a fix is needed (to provide context from best practices)

Detailed Validation Workflow Reference

For in-depth workflow details and error handling strategies, load the reference:

Read "$SKILL_DIR/references/validation_workflow.md"

This reference includes:

  • Detailed command options for each tool
  • Error handling strategies
  • Multi-resource file handling
  • Complete workflow diagram
  • Troubleshooting guide

When to load (ALWAYS load in these cases):

  • File contains 3 or more resources (multi-document YAML)
  • Validation produces errors you haven't seen before or can't immediately diagnose
  • Need to understand the complete workflow for debugging
  • Errors span multiple validation stages

Working with Multiple Resources

When a YAML file contains multiple resources (separated by ---):

  1. Validate the entire file first with yamllint and kubeconform
  2. If errors occur, identify which resource has issues by checking line numbers
  3. For dry-run, the file is tested as a unit (Kubernetes processes in order)
  4. Track issues per-resource when presenting findings to the user
Partial Parsing Behavior

When a multi-document YAML file has some valid and some invalid documents:

Expected behavior:

  • The CRD detection script (detect_crd.py) will parse valid documents and skip invalid ones
  • kubeconform will validate resources it can parse and report errors for unparseable ones
  • The validation report should clearly show which documents parsed and which failed

Example scenario: A file with 3 documents where document 1 has a syntax error:

  • Document 1 (Deployment): Syntax error at line 8
  • Document 2 (Service): Valid
  • Document 3 (Certificate CRD): Valid

Expected output:

  • CRD detection: Finds Certificate CRD from document 3
  • kubeconform: Reports error for document 1, validates documents 2 and 3
  • Report: Shows syntax error for document 1, validation results for documents 2 and 3

In your report:

| 文档 | 资源 | 解析 | 验证 |
|----------|----------|---------|------------|
| 1 | Deployment | ❌ 语法错误(第 8 行) | 已跳过 |
| 2 | Service | ✅ 已解析 | ✅ 有效 |
| 3 | Certificate | ✅ 已解析 | ✅ 有效 |

Line Number Reference Style:

  • Always use file-absolute line numbers (line numbers relative to the start of the entire file)
  • This matches what yamllint, kubeconform, and kubectl report
  • Example: If a file has 3 documents and the error is in document 2 which starts at line 35, report as "line 42" (the absolute line in the file), not "line 7" (relative to document start)
  • This consistency makes it easy for users to navigate directly to the error in their editor

This ensures users get maximum validation feedback even when some documents have issues.

Error Handling Strategies

Tool Not Available
  • Run bash "$SKILL_DIR/scripts/setup_tools.sh" to check availability
  • Provide installation instructions
  • Skip optional stages but document what was skipped
  • Continue with available tools
Cluster Access Issues
  • Attempt parse-only client-side dry-run with --dry-run=client --validate=false
  • Treat this fallback as transport/parsing signal only (--validate=false disables schema/type/required-field checks)
  • If client dry-run still fails with API discovery/openapi errors, skip dry-run and rely on lint/schema stages
  • Document limitations in validation report
CRD Documentation Not Found
  • Document that documentation lookup failed
  • Attempt validation with kubeconform CRD schemas
  • Suggest manual CRD inspection:
    kubectl get crd <crd-name>.group -o yaml
    kubectl explain <kind>
    
验证阶段失败
  • 即使某个阶段失败,也要继续进入下一阶段
  • 在向用户汇报之前收集所有错误
  • 优先修复较早阶段发现的错误

沟通指南

展示验证结果时:

  1. 清晰简洁地说明发现的问题

  2. 解释问题的影响(例如:“这会导致 Pod 创建失败”)

  3. 适时提供最佳实践方面的背景信息

  4. 将相关问题归类(例如:将所有缺少标签的问题归在一起)

  5. 所有问题都使用 file:line 格式的引用

  6. 说明修复的复杂程度——在问题标题中包含复杂度标记:

    • [简单]:单行修复,例如缩进、拼写错误或值更改
    • [中等]:多行修改或添加缺失字段/章节
    • [复杂]:逻辑变更、结构调整,或影响多个资源的修改

    问题标题格式示例:

    **Issue 1: deployment.yaml:8 - Wrong indentation (Error) [Simple]**
    **Issue 2: deployment.yaml:15-25 - Missing security context (Warning) [Medium]**
    **Issue 3: deployment.yaml - Selector mismatch with Service (Error) [Complex]**
    
  7. 始终提供全面的报告,包括:

    • 按阶段汇总所有问题的表格
    • 每个问题对应的修改前后代码块
    • 错误和警告的总数
    • 明确的用户后续步骤
  8. 绝不要主动提出应用修复——此工具严格用于报告

    • 不要询问“要我修复这个问题吗?”
    • 不要使用 AskUserQuestion 确认修复
    • 展示报告,让用户自行采取行动

性能优化

并行执行工具

为了提高验证速度,某些阶段可以并行执行:

可以并行执行(无依赖):

  • yamllint(阶段 2)和 detect_crd_wrapper.sh(阶段 3)可以同时运行
  • 这两个工具独立处理输入文件
  • 在继续进行架构验证之前,需要获取这两个工具的结果

并行执行示例:

# Run these in parallel (using & and wait, or parallel tool calls):
yamllint -c "$SKILL_DIR/assets/.yamllint" "$TARGET_FILE"
bash "$SKILL_DIR/scripts/detect_crd_wrapper.sh" "$TARGET_FILE"

必须按顺序执行:

  • 阶段 0(资源计数检查)→ 在所有其他阶段之前
  • 阶段 1(工具检查)→ 在使用任何工具之前
  • 阶段 4(架构验证)→ 在检测 CRD 之后(需要 CRD 信息作为上下文)
  • 阶段 5(试运行)→ 在架构验证之后
  • 阶段 6(报告)→ 在所有验证阶段完成之后

何时并行执行:

  • 资源数超过 5 个的文件最适合并行执行
  • 对于较小的文件(1–2 个资源),顺序执行即可

版本兼容性

始终考虑 Kubernetes 版本兼容性:

  • 检查已弃用的 API(例如,extensions/v1beta1 → apps/v1)
  • 对于 CRD,确保 apiVersion 与集群中的版本匹配
  • 使用 kubectl api-versions 列出集群中可用的 API 版本
  • 如果有版本专属文档,请参考该文档

测试覆盖指南

test/ 目录包含用于测试所有验证路径的示例文件。使用这些文件验证技能行为。

测试文件
测试文件用途预期行为
deployment-test.yaml有效的标准 K8s 资源所有阶段通过,无错误
certificate-crd-test.yaml有效的 CRD 资源检测到 CRD,执行 Context7 查询,无错误
comprehensive-test.yaml包含有意 YAML 语法错误的多资源文件检测到语法错误,部分解析成功,找到 CRD
schema-errors-test.yaml包含有意架构类型错误的有效 YAMLyamllint 通过;kubeconform 失败,并报告 2 个 JSON 路径错误(replicas、containerPort)
要测试的验证路径
  1. 正常路径(全部有效)
    • 文件:deployment-test.yaml
    • 预期:所有阶段通过,报告显示“0 个错误,0 个警告”
    • 命令:
cd "$SKILL_DIR"
python3 scripts/count_yaml_documents.py test/deployment-test.yaml
yamllint -c assets/.yamllint test/deployment-test.yaml
bash scripts/detect_crd_wrapper.sh test/deployment-test.yaml
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -strict -ignore-missing-schemas -summary -verbose \
  test/deployment-test.yaml
kubectl apply --dry-run=server -f test/deployment-test.yaml
  1. CRD 检测路径
    • 文件:certificate-crd-test.yaml
    • 预期:检测到 CRD,使用 mcp__context7__resolve-library-id 和 mcp__context7__query-docs
    • 命令:
cd "$SKILL_DIR"
python3 scripts/count_yaml_documents.py test/certificate-crd-test.yaml
bash scripts/detect_crd_wrapper.sh test/certificate-crd-test.yaml
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -strict -ignore-missing-schemas -summary -verbose \
  test/certificate-crd-test.yaml
  1. 语法错误路径
    • 文件:comprehensive-test.yaml
    • 预期:yamllint 捕获错误,kubeconform 报告部分验证结果,阻止试运行
    • 命令:
cd "$SKILL_DIR"
python3 scripts/count_yaml_documents.py test/comprehensive-test.yaml
yamllint -c assets/.yamllint test/comprehensive-test.yaml
bash scripts/detect_crd_wrapper.sh test/comprehensive-test.yaml
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -strict -ignore-missing-schemas -summary -verbose \
  test/comprehensive-test.yaml
kubectl apply --dry-run=server -f test/comprehensive-test.yaml
  1. 多资源部分解析
    • 文件:comprehensive-test.yaml(包含 3 个资源,其中 1 个有语法错误)
    • 预期:验证 3 个资源中的 2 个,并报告文档 1 存在解析错误
    • 命令:
cd "$SKILL_DIR"
python3 scripts/count_yaml_documents.py test/comprehensive-test.yaml
bash scripts/detect_crd_wrapper.sh test/comprehensive-test.yaml
  1. 架构验证错误路径(类型不匹配)
    • 文件:schema-errors-test.yaml
    • 预期:yamllint 通过(YAML 有效),kubeconform 失败,并报告 2 个 JSON 路径架构错误
    • 注意:kubeconform 报告的是 JSON 路径,而不是行号——请手动在 YAML 中定位字段
    • 命令:
cd "$SKILL_DIR"
python3 scripts/count_yaml_documents.py test/schema-errors-test.yaml
yamllint -c assets/.yamllint test/schema-errors-test.yaml
bash scripts/detect_crd_wrapper.sh test/schema-errors-test.yaml
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -strict -ignore-missing-schemas -summary -verbose \
  test/schema-errors-test.yaml
  1. 无法访问集群路径
    • 任意没有配置 kubectl 集群的有效文件
    • 预期:服务端试运行失败;尝试仅解析的客户端回退方式(不保证架构有效),若无法进行 API 发现,也可能失败
    • 命令:
cd "$SKILL_DIR"
KUBECONFIG=/tmp/nonexistent-kubeconfig kubectl apply --dry-run=server -f test/deployment-test.yaml
KUBECONFIG=/tmp/nonexistent-kubeconfig kubectl apply --dry-run=client --validate=false -f test/deployment-test.yaml
  1. 缺少工具路径
    • 测试时暂时从 PATH 中移除某个工具
    • 预期:setup_tools.sh 报告缺少的工具并打印安装说明,验证继续使用可用工具进行
    • 命令:
cd "$SKILL_DIR"
PATH="/usr/bin:/bin" bash scripts/setup_tools.sh
创建新的测试文件

添加测试文件时:

  1. 使用描述性文件名:<scenario>-test.yaml
  2. 在文件顶部的注释中说明预期行为
  3. 在错误路径测试中加入有意设置的错误
  4. 同时测试标准 K8s 资源和 CRD
预期报告结构

对于任何验证,报告都应包含:

  • 按严重程度统计问题数量的摘要表
  • 按阶段列出状态(已通过/失败/跳过)的表格
  • 文档解析表(适用于多资源文件)
  • 每个问题对应的修复前后代码块
  • 修复复杂度指标([Simple]、[Medium]、[Complex])
  • 文件绝对行号
  • “后续步骤”部分

完成标准

仅当以下所有条件都满足时,验证才算完成:

  • 阶段门按顺序进行评估,且每个跳过的阶段都说明了原因。
  • 资源数量来自 count_yaml_documents.py(或有记录的 AWK 回退方案)。
  • CRD 查询使用了 mcp__context7__resolve-library-id + mcp__context7__query-docs,仅在需要时才使用 web.search_query 作为回退方案。
  • 保持仅报告的边界(不进行编辑,也不提示应用修复)。
  • 输出包含运行过的确切命令、按严重程度分类的发现,以及手动后续步骤。

资源

scripts/

detect_crd_wrapper.sh

  • 处理 Python 依赖管理的包装脚本
  • 如果 PyYAML 不可用,会自动创建临时 venv
  • 调用 detect_crd.py 解析 YAML 文件
  • 用法:bash "$SKILL_DIR/scripts/detect_crd_wrapper.sh" "$TARGET_FILE"

detect_crd.py

  • 解析 YAML 文件以识别 Custom Resource Definitions
  • 提取 kind、apiVersion、group 和 version 信息
  • 输出供程序处理的 JSON
  • 需要 PyYAML(由包装脚本自动处理)
  • 可直接调用:python3 "$SKILL_DIR/scripts/detect_crd.py" "$TARGET_FILE"

count_yaml_documents.py

  • 以确定性方式统计多文档文件中非空 YAML 文档的数量
  • 返回包含文档数量和分隔符的 JSON
  • 在 Stage 1 之前使用,以决定是否加载深度工作流参考资料
  • 用法:python3 "$SKILL_DIR/scripts/count_yaml_documents.py" "$TARGET_FILE"

setup_tools.sh

  • 检查所需的验证工具
  • 提供缺失工具的安装说明
  • 验证已安装工具的版本
  • 用法:bash "$SKILL_DIR/scripts/setup_tools.sh"
references/

k8s_best_practices.md

  • Kubernetes YAML 最佳实践综合指南
  • 涵盖元数据、标签、资源限制和安全上下文
  • 常见验证问题及其修复方法
  • 在为验证错误提供背景信息时加载

validation_workflow.md

  • 包含所有阶段的详细验证工作流
  • 命令选项和配置
  • 错误处理策略
  • 完整的工作流图
  • 在复杂验证场景中加载
assets/

.yamllint

  • 为 Kubernetes YAML 预配置的 yamllint 规则
  • 遵循 Kubernetes 约定(2 个空格缩进、行长等)
  • 可按项目自定义
  • 用法:yamllint -c "$SKILL_DIR/assets/.yamllint" "$TARGET_FILE"

评论

支持 Markdown