helm-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Helm Chart Validator & Analysis Toolkit

Helm Chart 验证与分析工具包

Overview

概述

This skill provides a comprehensive validation and analysis workflow for Helm charts, combining Helm-native linting, template rendering, YAML validation, schema validation, CRD documentation lookup, and security best practices checking.
IMPORTANT: This is a READ-ONLY validator. It analyzes charts and proposes improvements but does NOT modify any files. All proposed changes are listed in the final summary for the user to review and apply manually or via the helm-generator skill.
本工具提供了一套针对Helm Chart的综合验证与分析工作流,整合了Helm原生检查、模板渲染、YAML验证、Schema校验、CRD文档查询以及安全最佳实践检查功能。
重要提示:这是一个只读验证工具。 它仅分析Chart并提出改进建议,不会修改任何文件。所有建议的更改都会在最终总结中列出,供用户手动审核或通过helm-generator工具应用。

When to Use This Skill

适用场景

Invoke this skill when:
  • Validating Helm charts before packaging or deployment
  • Debugging Helm template rendering errors
  • Testing chart templates with different values
  • Working with Custom Resource Definitions (CRDs) that need documentation
  • Implementing or refactoring Helm template helpers (
    _helpers.tpl
    )
  • Performing dry-run tests to catch admission controller errors
  • Ensuring charts follow Helm and Kubernetes best practices
  • Automating repetitive template patterns with Helm functions
  • The user asks to "validate", "lint", "check", "test", or "improve" Helm charts
  • Creating or optimizing template functions like
    include
    ,
    tpl
    ,
    required
    , etc.
在以下场景中调用本工具:
  • 在打包或部署前验证Helm Chart
  • 调试Helm模板渲染错误
  • 使用不同值测试Chart模板
  • 处理需要文档支持的Custom Resource Definitions (CRDs)
  • 实现或重构Helm模板助手(
    _helpers.tpl
  • 执行预演测试以捕获准入控制器错误
  • 确保Chart遵循Helm和Kubernetes最佳实践
  • 使用Helm函数自动化重复的模板模式
  • 用户要求“验证”“检查”“测试”或“改进”Helm Chart时
  • 创建或优化
    include
    tpl
    required
    等模板函数

Validation & Testing Workflow

验证与测试工作流

Follow this sequential validation workflow. Each stage catches different types of issues:
遵循以下顺序验证工作流,每个阶段会捕获不同类型的问题:

Stage 1: Tool Check

阶段1:工具检查

Before starting validation, verify required tools are installed:
bash
bash scripts/setup_tools.sh
Required tools:
  • helm: Helm package manager for Kubernetes (v3+)
  • yamllint: YAML syntax and style linting
  • kubeconform: Kubernetes schema validation with CRD support
  • kubectl: Cluster dry-run testing (optional but recommended)
If tools are missing, provide installation instructions from the script output and ask the user if they want to install them.
开始验证前,先确认所需工具已安装:
bash
bash scripts/setup_tools.sh
所需工具:
  • helm:Kubernetes的Helm包管理器(v3+版本)
  • yamllint:YAML语法与风格检查工具
  • kubeconform:支持CRD的Kubernetes Schema验证工具
  • kubectl:集群预演测试工具(可选但推荐)
如果缺少工具,会从脚本输出中提供安装说明,并询问用户是否需要安装。

Stage 2: Helm Chart Structure Validation

阶段2:Helm Chart结构验证

Verify the chart follows the standard Helm directory structure:
bash
bash scripts/validate_chart_structure.sh <chart-directory>
Expected structure:
mychart/
  Chart.yaml          # Chart metadata (required)
  values.yaml         # Default values (required)
  values.schema.json  # JSON Schema for values validation (optional)
  templates/          # Template directory (required)
    _helpers.tpl      # Template helpers (recommended)
    NOTES.txt         # Post-install notes (recommended)
    *.yaml            # Kubernetes manifest templates
  charts/             # Chart dependencies (optional)
  crds/               # Custom Resource Definitions (optional)
  .helmignore         # Files to ignore during packaging (optional)
Common issues caught:
  • Missing required files (Chart.yaml, values.yaml, templates/)
  • Invalid Chart.yaml syntax or missing required fields
  • Malformed values.schema.json
  • Incorrect file permissions
验证Chart是否遵循标准Helm目录结构:
bash
bash scripts/validate_chart_structure.sh <chart-directory>
预期结构:
mychart/
  Chart.yaml          # Chart元数据(必填)
  values.yaml         # 默认配置值(必填)
  values.schema.json  # 配置值的JSON Schema验证(可选)
  templates/          # 模板目录(必填)
    _helpers.tpl      # 模板助手(推荐)
    NOTES.txt         # 安装后说明(推荐)
    *.yaml            # Kubernetes清单模板
  charts/             # Chart依赖(可选)
  crds/               # Custom Resource Definitions(可选)
  .helmignore         # 打包时忽略的文件(可选)
常见问题:
  • 缺少必填文件(Chart.yaml、values.yaml、templates/)
  • Chart.yaml语法无效或缺少必填字段
  • values.schema.json格式错误
  • 文件权限不正确

Stage 3: Helm Lint

阶段3:Helm检查

Run Helm's built-in linter to catch chart-specific issues:
bash
helm lint <chart-directory> --strict
Optional flags:
  • --values <values-file>
    : Test with specific values
  • --set key=value
    : Override specific values
  • --debug
    : Show detailed error information
Common issues caught:
  • Invalid Chart.yaml metadata
  • Template syntax errors
  • Missing or undefined values
  • Deprecated Kubernetes API versions
  • Chart best practice violations
Auto-fix approach:
  • For template errors, identify the problematic template file
  • Show the user the specific line causing issues
  • Propose fixes using the Edit tool
  • Re-run
    helm lint
    after fixes
运行Helm内置的检查工具捕获Chart特定问题:
bash
helm lint <chart-directory> --strict
可选参数:
  • --values <values-file>
    :使用指定的配置文件测试
  • --set key=value
    :覆盖特定配置值
  • --debug
    :显示详细错误信息
常见问题:
  • Chart.yaml元数据无效
  • 模板语法错误
  • 配置值未定义或缺失
  • Kubernetes API版本已弃用
  • 违反Helm最佳实践
自动修复方法:
  • 对于模板错误,定位问题模板文件
  • 向用户展示导致问题的具体行
  • 建议使用编辑工具进行修复
  • 修复后重新运行
    helm lint

Stage 4: Template Rendering

阶段4:模板渲染

Render templates locally to verify they produce valid YAML:
bash
helm template <release-name> <chart-directory> \
  --values <values-file> \
  --debug \
  --output-dir ./rendered
Options to consider:
  • --values values.yaml
    : Use specific values file
  • --set key=value
    : Override individual values
  • --show-only templates/deployment.yaml
    : Render specific template
  • --validate
    : Validate against Kubernetes OpenAPI schema
  • --include-crds
    : Include CRDs in rendered output
  • --is-upgrade
    : Simulate upgrade scenario
  • --kube-version 1.28.0
    : Target specific Kubernetes version
Common issues caught:
  • Template syntax errors (Go template issues)
  • Undefined variables or values
  • Type mismatches (string vs. integer)
  • Missing required values
  • Logic errors in conditionals or loops
  • Incorrect indentation in nested templates
For template errors:
  • Identify the template file and line number
  • Check if values are properly defined in values.yaml
  • Verify template function usage (quote, required, default, include, etc.)
  • Test with different value combinations
在本地渲染模板,验证其是否生成有效的YAML:
bash
helm template <release-name> <chart-directory> \
  --values <values-file> \
  --debug \
  --output-dir ./rendered
可选配置:
  • --values values.yaml
    :使用特定配置文件
  • --set key=value
    :覆盖单个配置值
  • --show-only templates/deployment.yaml
    :仅渲染指定模板
  • --validate
    :针对Kubernetes OpenAPI Schema进行验证
  • --include-crds
    :在渲染输出中包含CRD
  • --is-upgrade
    :模拟升级场景
  • --kube-version 1.28.0
    :针对特定Kubernetes版本
常见问题:
  • 模板语法错误(Go模板问题)
  • 变量或配置值未定义
  • 类型不匹配(字符串 vs 整数)
  • 缺少必填配置值
  • 条件或循环中的逻辑错误
  • 嵌套模板中的缩进错误
处理模板错误:
  • 定位模板文件和行号
  • 检查values.yaml中是否正确定义了配置值
  • 验证模板函数的使用(quote、required、default、include等)
  • 使用不同的配置组合进行测试

Stage 5: YAML Syntax Validation

阶段5:YAML语法验证

Validate YAML syntax and formatting of rendered templates:
bash
yamllint -c assets/.yamllint ./rendered/*.yaml
Common issues caught:
  • Indentation errors (tabs vs spaces)
  • Trailing whitespace
  • Line length violations
  • Syntax errors
  • Duplicate keys
  • Document start/end markers
Auto-fix approach:
  • For simple issues (indentation, trailing spaces), propose fixes using the Edit tool
  • For template-generated issues, fix the source template, not rendered output
  • Always show the user what will be changed before applying fixes
验证渲染后模板的YAML语法与格式:
bash
yamllint -c assets/.yamllint ./rendered/*.yaml
常见问题:
  • 缩进错误(制表符 vs 空格)
  • 尾随空格
  • 行长度超出限制
  • 语法错误
  • 重复键
  • 文档开始/结束标记问题
自动修复方法:
  • 对于简单问题(缩进、尾随空格),建议使用编辑工具修复
  • 对于模板生成的问题,修复源模板而非渲染后的输出
  • 在应用修复前,始终向用户展示将要更改的内容

Stage 6: CRD Detection and Documentation Lookup

阶段6:CRD检测与文档查询

Before schema validation, detect if the chart contains or renders Custom Resource Definitions:
bash
undefined
在Schema验证前,检测Chart是否包含或渲染了Custom Resource Definitions:
bash
undefined

Check crds/ directory

检查crds/目录

bash scripts/detect_crd_wrapper.sh <chart-directory>/crds/*.yaml
bash scripts/detect_crd_wrapper.sh <chart-directory>/crds/*.yaml

Check rendered templates

检查渲染后的模板

bash scripts/detect_crd_wrapper.sh ./rendered/*.yaml

The script outputs JSON with resource information:
```json
[
  {
    "kind": "Certificate",
    "apiVersion": "cert-manager.io/v1",
    "group": "cert-manager.io",
    "version": "v1",
    "isCRD": true,
    "name": "example-cert"
  }
]
For each detected CRD:
  1. Try context7 MCP first (preferred):
    Use mcp__context7__resolve-library-id with the CRD project name
    Example: "cert-manager" for cert-manager.io CRDs
             "prometheus-operator" for monitoring.coreos.com CRDs
             "istio" for networking.istio.io CRDs
    
    Then use mcp__context7__get-library-docs with:
    - context7CompatibleLibraryID from resolve step
    - topic: The CRD kind and relevant features (e.g., "Certificate spec")
    - tokens: 5000 (adjust based on need)
  2. Fallback to WebSearch if context7 fails:
    Search query pattern:
    "<kind>" "<group>" kubernetes CRD "<version>" documentation spec
    
    Example:
    "Certificate" "cert-manager.io" kubernetes CRD "v1" documentation spec
    "Prometheus" "monitoring.coreos.com" kubernetes CRD "v1" documentation spec
  3. Extract key information:
    • Required fields in
      spec
    • Field types and validation rules
    • Examples from documentation
    • Version-specific changes or deprecations
    • Common configuration patterns
Why this matters: CRDs have custom schemas not available in standard Kubernetes validation tools. Understanding the CRD's spec requirements prevents validation errors and ensures correct resource configuration.
bash scripts/detect_crd_wrapper.sh ./rendered/*.yaml

脚本会输出包含资源信息的JSON:
```json
[
  {
    "kind": "Certificate",
    "apiVersion": "cert-manager.io/v1",
    "group": "cert-manager.io",
    "version": "v1",
    "isCRD": true,
    "name": "example-cert"
  }
]
对于每个检测到的CRD:
  1. 优先使用context7 MCP:
    使用mcp__context7__resolve-library-id传入CRD项目名称
    示例:cert-manager.io CRD传入"cert-manager"
             monitoring.coreos.com CRD传入"prometheus-operator"
             networking.istio.io CRD传入"istio"
    
    然后使用mcp__context7__get-library-docs,参数包括:
    - resolve步骤得到的context7CompatibleLibraryID
    - topic:CRD类型和相关特性(例如"Certificate spec")
    - tokens:5000(根据需要调整)
  2. 如果context7失败,回退到Web搜索:
    搜索查询格式:
    "<kind>" "<group>" kubernetes CRD "<version>" documentation spec
    
    示例:
    "Certificate" "cert-manager.io" kubernetes CRD "v1" documentation spec
    "Prometheus" "monitoring.coreos.com" kubernetes CRD "v1" documentation spec
  3. 提取关键信息:
    • spec
      中的必填字段
    • 字段类型和验证规则
    • 文档中的示例
    • 版本特定的变更或弃用信息
    • 常见配置模式
为什么这很重要: CRD具有标准Kubernetes验证工具中没有的自定义Schema。了解CRD的spec要求可以避免验证错误,确保资源配置正确。

Stage 7: Schema Validation

阶段7:Schema验证

Validate rendered templates against Kubernetes schemas:
bash
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -summary \
  -verbose \
  ./rendered/*.yaml
Options to consider:
  • Add
    -strict
    to reject unknown fields (recommended for production)
  • Add
    -ignore-missing-schemas
    if working with custom/internal CRDs
  • Add
    -kubernetes-version 1.28.0
    to validate against specific K8s version
  • Add
    -output json
    for programmatic processing
Common issues caught:
  • Invalid apiVersion or kind
  • Missing required fields
  • Wrong field types
  • Invalid enum values
  • Unknown fields (with -strict)
For CRDs: If kubeconform reports "no schema found", this is expected. Use the documentation from Stage 6 to manually validate the spec fields.
针对Kubernetes Schema验证渲染后的模板:
bash
kubeconform \
  -schema-location default \
  -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
  -summary \
  -verbose \
  ./rendered/*.yaml
可选配置:
  • 添加
    -strict
    以拒绝未知字段(生产环境推荐)
  • 如果使用自定义/内部CRD,添加
    -ignore-missing-schemas
  • 添加
    -kubernetes-version 1.28.0
    以针对特定K8s版本验证
  • 添加
    -output json
    以支持程序化处理
常见问题:
  • apiVersion或kind无效
  • 缺少必填字段
  • 字段类型错误
  • 枚举值无效
  • 存在未知字段(使用-strict参数时)
对于CRD: 如果kubeconform报告“未找到schema”,这是正常现象。使用阶段6的文档手动验证spec字段。

Stage 8: Cluster Dry-Run (if available)

阶段8:集群预演(如果可用)

If kubectl is configured and cluster access is available, perform a server-side dry-run:
bash
undefined
如果已配置kubectl且具有集群访问权限,执行服务器端预演:
bash
undefined

Test installation

测试安装

helm install <release-name> <chart-directory>
--dry-run
--debug
--values <values-file>
helm install <release-name> <chart-directory>
--dry-run
--debug
--values <values-file>

Test upgrade

测试升级

helm upgrade <release-name> <chart-directory>
--dry-run
--debug
--values <values-file>

**This catches:**
- Admission controller rejections
- Policy violations (PSP, OPA, Kyverno, etc.)
- Resource quota violations
- Missing namespaces
- Invalid ConfigMap/Secret references
- Webhook validations
- Existing resource conflicts

**If dry-run is not possible:**
- Use kubectl with rendered templates: `kubectl apply --dry-run=server -f ./rendered/`
- Skip if no cluster access
- Document that cluster-specific validation was skipped

**For updates to existing releases:**
```bash
helm diff upgrade <release-name> <chart-directory>
This shows what would change, helping catch unintended modifications. (Requires helm-diff plugin)
helm upgrade <release-name> <chart-directory>
--dry-run
--debug
--values <values-file>

**此阶段捕获的问题:**
- 准入控制器拒绝
- 策略违反(PSP、OPA、Kyverno等)
- 资源配额违反
- 命名空间缺失
- ConfigMap/Secret引用无效
- Webhook验证失败
- 现有资源冲突

**如果无法执行预演:**
- 使用kubectl处理渲染后的模板:`kubectl apply --dry-run=server -f ./rendered/`
- 如果没有集群访问权限则跳过
- 在验证报告中记录跳过的原因

**对于现有版本的更新:**
```bash
helm diff upgrade <release-name> <chart-directory>
这会显示将要发生的变更,帮助捕获意外修改。(需要helm-diff插件)

Stage 9: Security Best Practices Check (MANDATORY)

阶段9:安全最佳实践检查(必填)

IMPORTANT: This stage is MANDATORY. Analyze rendered templates for security best practices compliance.
Check rendered Deployment/Pod templates for:
  1. Missing securityContext - Look for pods/containers without security settings:
    yaml
    # Check if pod-level securityContext exists
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
  2. Missing container securityContext - Each container should have:
    yaml
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      runAsNonRoot: true
      capabilities:
        drop:
          - ALL
  3. Missing resource limits/requests - Check for:
    yaml
    resources:
      limits:
        cpu: "100m"
        memory: "128Mi"
      requests:
        cpu: "100m"
        memory: "128Mi"
  4. Image tag issues - Flag if using
    :latest
    or no tag
  5. Missing probes - Check for liveness/readiness probes
How to check: Read the rendered deployment YAML files and grep for these patterns:
bash
undefined
重要提示: 此阶段为必填项。分析渲染后的模板是否符合安全最佳实践。
检查渲染后的Deployment/Pod模板是否存在以下问题:
  1. 缺少securityContext - 查找没有安全设置的Pod/容器:
    yaml
    # 检查是否存在Pod级别的securityContext
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
  2. 缺少容器securityContext - 每个容器应包含:
    yaml
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      runAsNonRoot: true
      capabilities:
        drop:
          - ALL
  3. 缺少资源限制/请求 - 检查是否包含:
    yaml
    resources:
      limits:
        cpu: "100m"
        memory: "128Mi"
      requests:
        cpu: "100m"
        memory: "128Mi"
  4. 镜像标签问题 - 标记使用
    :latest
    或未指定标签的情况
  5. 缺少探针 - 检查是否存在存活/就绪探针
检查方法: 读取渲染后的Deployment YAML文件,使用grep查找这些模式:
bash
undefined

Check for securityContext

检查securityContext

grep -l "securityContext" ./rendered/*.yaml
grep -l "securityContext" ./rendered/*.yaml

Check for resources

检查资源配置

grep -l "resources:" ./rendered/*.yaml
grep -l "resources:" ./rendered/*.yaml

Check for latest tag

检查latest标签

grep "image:.:latest" ./rendered/.yaml
undefined
grep "image:.:latest" ./rendered/.yaml
undefined

Stage 10: Final Report (MANDATORY)

阶段10:最终报告(必填)

IMPORTANT: This stage is MANDATORY even if all validations pass. You MUST complete ALL of the following actions.
This is a READ-ONLY validator. Do NOT modify any files. List all proposed changes in the summary.
重要提示: 即使所有验证都通过,此阶段也为必填项。你必须完成以下所有操作。
这是一个只读验证工具,不要修改任何文件。在总结中列出所有建议的更改。

Step 1: Load Reference Files (MANDATORY when warnings exist)

步骤1:加载参考文件(当存在警告时必填)

If ANY warnings, errors, or security issues were found, you MUST read:
Read references/helm_best_practices.md
Read references/k8s_best_practices.md
Use these references to provide context and recommendations for each issue found.
如果发现任何警告、错误或安全问题,必须读取:
Read references/helm_best_practices.md
Read references/k8s_best_practices.md
使用这些参考资料为每个发现的问题提供背景信息和建议。

Step 2: Present Validation Summary

步骤2:呈现验证总结

Always present a validation summary formatted as a table showing:
  • Each validation stage executed (Stages 1-9)
  • Status of each stage (✅ Passed, ⚠️ Warning, ❌ Failed)
  • Count of issues found per stage
Example:
| Stage | Status | Issues |
|-------|--------|--------|
| 1. Tool Check | ✅ Passed | All tools available |
| 2. Structure | ⚠️ Warning | Missing: .helmignore, NOTES.txt |
| 3. Helm Lint | ✅ Passed | 0 errors |
| 4. Template Render | ✅ Passed | 5 templates rendered |
| 5. YAML Syntax | ✅ Passed | No yamllint errors |
| 6. CRD Detection | ✅ Passed | 1 CRD documented |
| 7. Schema Validation | ✅ Passed | All resources valid |
| 8. Dry-Run | ✅ Passed | No cluster errors |
| 9. Security Check | ⚠️ Warning | Missing securityContext |
始终以表格形式呈现验证总结,包含:
  • 已执行的每个验证阶段(阶段1-9)
  • 每个阶段的状态(✅ 通过,⚠️ 警告,❌ 失败)
  • 每个阶段发现的问题数量
示例:
| 阶段 | 状态 | 问题 |
|-------|--------|--------|
| 1. 工具检查 | ✅ 通过 | 所有工具已就绪 |
| 2. 结构检查 | ⚠️ 警告 | 缺失:.helmignore、NOTES.txt |
| 3. Helm检查 | ✅ 通过 | 0个错误 |
| 4. 模板渲染 | ✅ 通过 | 已渲染5个模板 |
| 5. YAML语法 | ✅ 通过 | 无yamllint错误 |
| 6. CRD检测 | ✅ 通过 | 已记录1个CRD |
| 7. Schema验证 | ✅ 通过 | 所有资源有效 |
| 8. 预演测试 | ✅ 通过 | 无集群错误 |
| 9. 安全检查 | ⚠️ 警告 | 缺少securityContext |

Step 3: Categorize All Issues

步骤3:分类所有问题

Group findings by severity:
❌ Errors (must fix):
  • Template syntax errors
  • Missing required fields
  • Schema validation failures
  • Dry-run failures
⚠️ Warnings (should fix):
  • Deprecated Kubernetes APIs
  • Missing securityContext
  • Missing resource limits/requests
  • Using
    :latest
    image tag
  • Missing recommended files (_helpers.tpl, .helmignore, NOTES.txt)
ℹ️ Info (recommendations):
  • Missing values.schema.json
  • Missing README.md
  • Optimization opportunities
按严重程度分组发现的问题:
❌ 错误(必须修复):
  • 模板语法错误
  • 缺少必填字段
  • Schema验证失败
  • 预演测试失败
⚠️ 警告(应该修复):
  • Kubernetes API已弃用
  • 缺少securityContext
  • 缺少资源限制/请求
  • 使用
    :latest
    镜像标签
  • 缺少推荐文件(_helpers.tpl、.helmignore、NOTES.txt)
ℹ️ 信息(建议):
  • 缺少values.schema.json
  • 缺少README.md
  • 优化机会

Step 4: List Proposed Changes (DO NOT APPLY)

步骤4:列出建议的更改(不要应用)

For each issue, provide a proposed fix with:
  • File path and line number (if applicable)
  • Before/after code blocks
  • Explanation of why this change is recommended
Example format:
undefined
对于每个问题,提供建议的修复方案,包含:
  • 文件路径和行号(如果适用)
  • 修复前后的代码块
  • 解释为什么建议进行此更改
示例格式:
undefined

Proposed Changes

建议的更改

1. Add securityContext to Deployment

1. 为Deployment添加securityContext

File: templates/deployment.yaml:25 Severity: ⚠️ Warning Reason: Running containers as root is a security risk
Current:
yaml
spec:
  containers:
    - name: app
      image: nginx:1.21
Proposed:
yaml
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 2000
  containers:
    - name: app
      image: nginx:1.21
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop:
            - ALL
文件: templates/deployment.yaml:25 严重程度: ⚠️ 警告 原因: 以root身份运行容器存在安全风险
当前代码:
yaml
spec:
  containers:
    - name: app
      image: nginx:1.21
建议代码:
yaml
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    fsGroup: 2000
  containers:
    - name: app
      image: nginx:1.21
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop:
            - ALL

2. Add .helmignore file

2. 添加.helmignore文件

File: .helmignore (new file) Severity: ⚠️ Warning Reason: Excludes unnecessary files from chart packaging
Proposed: Copy from
assets/.helmignore
undefined
文件: .helmignore(新文件) 严重程度: ⚠️ 警告 原因: 从Chart打包中排除不必要的文件
建议:
assets/.helmignore
复制
undefined

Step 5: Automation Opportunities

步骤5:自动化机会

List all detected automation opportunities:
  • If
    _helpers.tpl
    is missing → Recommend:
    bash scripts/generate_helpers.sh <chart>
  • If
    .helmignore
    is missing → Recommend: Copy from
    assets/.helmignore
  • If
    values.schema.json
    is missing → Recommend: Copy and customize from
    assets/values.schema.json
  • If
    NOTES.txt
    is missing → Recommend: Create post-install notes template
  • If
    README.md
    is missing → Recommend: Create chart documentation
列出所有检测到的自动化机会:
  • 如果缺少
    _helpers.tpl
    → 建议:
    bash scripts/generate_helpers.sh <chart>
  • 如果缺少
    .helmignore
    → 建议:从
    assets/.helmignore
    复制
  • 如果缺少
    values.schema.json
    → 建议:从
    assets/values.schema.json
    复制并自定义
  • 如果缺少
    NOTES.txt
    → 建议:创建安装后说明模板
  • 如果缺少
    README.md
    → 建议:创建Chart文档

Step 6: Final Summary

步骤6:最终总结

Provide a final summary:
undefined
提供最终总结:
undefined

Validation Summary

验证总结

Chart: <chart-name> Status: ⚠️ Warnings Found (or ✅ Ready for Deployment)
Issues Found:
  • Errors: X
  • Warnings: Y
  • Info: Z
Proposed Changes: N changes recommended
Next Steps:
  1. Review proposed changes above
  2. Apply changes manually or use helm-generator skill
  3. Re-run validation to confirm fixes
undefined
Chart: <chart-name> 状态: ⚠️ 发现警告(或 ✅ 可部署)
发现的问题:
  • 错误:X个
  • 警告:Y个
  • 信息:Z个
建议的更改: 共N项建议
下一步:
  1. 查看上述建议的更改
  2. 手动应用更改或使用helm-generator工具
  3. 重新运行验证以确认修复
undefined

Helm Templating Automation & Best Practices

Helm模板自动化与最佳实践

This section covers advanced Helm templating techniques, helper functions, and automation strategies.
本节涵盖高级Helm模板技术、助手函数和自动化策略。

Template Helpers (
_helpers.tpl
)

模板助手(
_helpers.tpl

Template helpers are reusable functions defined in
templates/_helpers.tpl
. They promote DRY principles and consistency.
Standard helper patterns:
  1. Chart name helper:
yaml
{{/*
Expand the name of the chart.
*/}}
{{- define "mychart.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
  1. Fullname helper:
yaml
{{/*
Create a default fully qualified app name.
*/}}
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
  1. Chart reference helper:
yaml
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "mychart.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
  1. Standard labels helper:
yaml
{{/*
Common labels
*/}}
{{- define "mychart.labels" -}}
helm.sh/chart: {{ include "mychart.chart" . }}
{{ include "mychart.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
  1. Selector labels helper:
yaml
{{/*
Selector labels
*/}}
{{- define "mychart.selectorLabels" -}}
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
  1. ServiceAccount name helper:
yaml
{{/*
Create the name of the service account to use
*/}}
{{- define "mychart.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "mychart.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
When to create helpers:
  • Values used in multiple templates
  • Complex logic that's repeated
  • Label sets that should be consistent
  • Name generation patterns
  • Conditional resource inclusion
模板助手是定义在
templates/_helpers.tpl
中的可重用函数,遵循DRY原则并确保一致性。
标准助手模式:
  1. Chart名称助手:
yaml
{{/*
扩展Chart的名称。
*/}}
{{- define "mychart.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
  1. 全名助手:
yaml
{{/*
创建默认的完全限定应用名称。
*/}}
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
  1. Chart引用助手:
yaml
{{/*
创建Chart标签中使用的Chart名称和版本。
*/}}
{{- define "mychart.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
  1. 标准标签助手:
yaml
{{/*
通用标签
*/}}
{{- define "mychart.labels" -}}
helm.sh/chart: {{ include "mychart.chart" . }}
{{ include "mychart.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
  1. 选择器标签助手:
yaml
{{/*
选择器标签
*/}}
{{- define "mychart.selectorLabels" -}}
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
  1. ServiceAccount名称助手:
yaml
{{/*
创建要使用的ServiceAccount名称
*/}}
{{- define "mychart.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "mychart.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
何时创建助手:
  • 在多个模板中使用的值
  • 重复的复杂逻辑
  • 应保持一致的标签集
  • 名称生成模式
  • 条件性资源包含

Essential Template Functions

必备模板函数

Reference and use these Helm template functions for robust charts:
  1. required
    - Enforce required values:
yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ required "A valid service name is required!" .Values.service.name }}
  1. default
    - Provide fallback values:
yaml
replicas: {{ .Values.replicaCount | default 1 }}
  1. quote
    - Safely quote string values:
yaml
env:
  - name: DATABASE_HOST
    value: {{ .Values.database.host | quote }}
  1. include
    - Use helpers with pipeline:
yaml
metadata:
  labels:
    {{- include "mychart.labels" . | nindent 4 }}
  1. tpl
    - Render strings as templates:
yaml
{{- tpl .Values.customConfig . }}
  1. toYaml
    - Convert objects to YAML:
yaml
{{- with .Values.resources }}
resources:
  {{- toYaml . | nindent 2 }}
{{- end }}
  1. fromYaml
    - Parse YAML strings:
yaml
{{- $config := .Values.configYaml | fromYaml }}
  1. merge
    - Merge maps:
yaml
{{- $merged := merge .Values.override .Values.defaults }}
  1. lookup
    - Query cluster resources (use carefully):
yaml
{{- $secret := lookup "v1" "Secret" .Release.Namespace "my-secret" }}
{{- if $secret }}
  # Secret exists, use it
{{- else }}
  # Create new secret
{{- end }}
参考并使用以下Helm模板函数创建健壮的Chart:
  1. required
    - 强制必填值:
yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ required "必须提供有效的服务名称!" .Values.service.name }}
  1. default
    - 提供回退值:
yaml
replicas: {{ .Values.replicaCount | default 1 }}
  1. quote
    - 安全地为字符串值添加引号:
yaml
env:
  - name: DATABASE_HOST
    value: {{ .Values.database.host | quote }}
  1. include
    - 通过管道使用助手:
yaml
metadata:
  labels:
    {{- include "mychart.labels" . | nindent 4 }}
  1. tpl
    - 将字符串作为模板渲染:
yaml
{{- tpl .Values.customConfig . }}
  1. toYaml
    - 将对象转换为YAML:
yaml
{{- with .Values.resources }}
resources:
  {{- toYaml . | nindent 2 }}
{{- end }}
  1. fromYaml
    - 解析YAML字符串:
yaml
{{- $config := .Values.configYaml | fromYaml }}
  1. merge
    - 合并映射:
yaml
{{- $merged := merge .Values.override .Values.defaults }}
  1. lookup
    - 查询集群资源(谨慎使用):
yaml
{{- $secret := lookup "v1" "Secret" .Release.Namespace "my-secret" }}
{{- if $secret }}
  # Secret已存在,使用它
{{- else }}
  # 创建新的Secret
{{- end }}

Advanced Template Patterns

高级模板模式

  1. Conditional resource creation:
yaml
{{- if .Values.ingress.enabled -}}
apiVersion: networking.k8s.io/v1
kind: Ingress
  1. 条件性资源创建:
yaml
{{- if .Values.ingress.enabled -}}
apiVersion: networking.k8s.io/v1
kind: Ingress

... ingress definition

... Ingress定义

{{- end }}

2. **Range over lists:**
```yaml
{{- range .Values.extraEnvVars }}
- name: {{ .name }}
  value: {{ .value | quote }}
{{- end }}
  1. Range over maps:
yaml
{{- range $key, $value := .Values.configMap }}
{{ $key }}: {{ $value | quote }}
{{- end }}
  1. With blocks for scoping:
yaml
{{- with .Values.nodeSelector }}
nodeSelector:
  {{- toYaml . | nindent 2 }}
{{- end }}
  1. Named templates with custom context:
yaml
{{- include "mychart.container" (dict "root" . "container" .Values.mainContainer) }}
{{- end }}

2. **遍历列表:**
```yaml
{{- range .Values.extraEnvVars }}
- name: {{ .name }}
  value: {{ .value | quote }}
{{- end }}
  1. 遍历映射:
yaml
{{- range $key, $value := .Values.configMap }}
{{ $key }}: {{ $value | quote }}
{{- end }}
  1. 使用With块进行作用域限定:
yaml
{{- with .Values.nodeSelector }}
nodeSelector:
  {{- toYaml . | nindent 2 }}
{{- end }}
  1. 带自定义上下文的命名模板:
yaml
{{- include "mychart.container" (dict "root" . "container" .Values.mainContainer) }}

Values Structure Best Practices

配置值结构最佳实践

Prefer flat structures when possible:
yaml
undefined
尽可能使用扁平化结构:
yaml
undefined

Good - Flat structure

推荐 - 扁平化结构

serverName: nginx serverPort: 80
serverName: nginx serverPort: 80

Acceptable - Nested structure for related settings

可接受 - 相关设置使用嵌套结构

server: name: nginx port: 80 replicas: 3

**Always provide defaults in values.yaml:**
```yaml
replicaCount: 1

image:
  repository: nginx
  pullPolicy: IfNotPresent
  tag: "1.21.0"

service:
  type: ClusterIP
  port: 80

resources:
  limits:
    cpu: 100m
    memory: 128Mi
  requests:
    cpu: 100m
    memory: 128Mi
Document all values:
yaml
undefined
server: name: nginx port: 80 replicas: 3

**始终在values.yaml中提供默认值:**
```yaml
replicaCount: 1

image:
  repository: nginx
  pullPolicy: IfNotPresent
  tag: "1.21.0"

service:
  type: ClusterIP
  port: 80

resources:
  limits:
    cpu: 100m
    memory: 128Mi
  requests:
    cpu: 100m
    memory: 128Mi
为所有配置值添加文档:
yaml
undefined

replicaCount is the number of pod replicas for the deployment

replicaCount是Deployment的Pod副本数量

replicaCount: 1
replicaCount: 1

image configures the container image

image配置容器镜像

image:

image.repository is the container image registry and name

repository: nginx

image.tag overrides the image tag (default is chart appVersion)

tag: "1.21.0"
undefined
image:

image.repository是容器镜像的仓库和名称

repository: nginx

image.tag覆盖镜像标签(默认是Chart的appVersion)

tag: "1.21.0"
undefined

Template Comments and Documentation

模板注释与文档

Use Helm template comments for documentation:
yaml
{{- /*
mychart.fullname generates the fullname for resources.
It supports nameOverride and fullnameOverride values.
Usage: {{ include "mychart.fullname" . }}
*/ -}}
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
Use YAML comments for user-facing notes:
yaml
undefined
使用Helm模板注释进行文档说明:
yaml
{{- /*
mychart.fullname为资源生成全名。
它支持nameOverride和fullnameOverride配置值。
用法:{{ include "mychart.fullname" . }}
*/ -}}
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
使用YAML注释为用户提供说明:
yaml
undefined

WARNING: Changing the storage class will not migrate existing data

警告:更改存储类不会迁移现有数据

storageClass: "standard"
undefined
storageClass: "standard"
undefined

Whitespace Management

空白字符管理

Use
-
to chomp whitespace in template directives:
yaml
{{- if .Values.enabled }}
  # Remove leading whitespace
{{- end }}

{{ .Values.name -}}
  # Remove trailing whitespace
Good formatting:
yaml
{{- if .Values.enabled }}
  key: value
{{- end }}
Bad formatting:
yaml
{{if .Values.enabled}}
key: value
{{end}}
在模板指令中使用
-
去除空白字符:
yaml
{{- if .Values.enabled }}
  # 去除前导空白字符
{{- end }}

{{ .Values.name -}}
  # 去除尾随空白字符
良好的格式:
yaml
{{- if .Values.enabled }}
  key: value
{{- end }}
不良的格式:
yaml
{{if .Values.enabled}}
key: value
{{end}}

Helper Patterns Reference

助手模式参考

When analyzing charts, identify opportunities for helper functions:
  1. Identify repetition:
    • Same label sets across resources
    • Repeated name generation logic
    • Common conditional patterns
  2. Common helper patterns to recommend:
    • Chart name helper (
      .name
      )
    • Fullname helper (
      .fullname
      )
    • Chart version label (
      .chart
      )
    • Common labels (
      .labels
      )
    • Selector labels (
      .selectorLabels
      )
    • ServiceAccount name (
      .serviceAccountName
      )
  3. When to recommend helpers:
    • Missing
      _helpers.tpl
      file
    • Repeated code patterns across templates
    • Inconsistent label usage
    • Long resource names that need truncation
分析Chart时,识别创建助手函数的机会:
  1. 识别重复内容:
    • 跨资源的相同标签集
    • 重复的名称生成逻辑
    • 常见的条件模式
  2. 建议的常见助手模式:
    • Chart名称助手(
      .name
    • 全名助手(
      .fullname
    • Chart版本标签(
      .chart
    • 通用标签(
      .labels
    • 选择器标签(
      .selectorLabels
    • ServiceAccount名称(
      .serviceAccountName
  3. 何时建议创建助手:
    • 缺少
      _helpers.tpl
      文件
    • 跨模板的重复代码模式
    • 标签使用不一致
    • 需要截断的长资源名称

Best Practices Reference

最佳实践参考

For detailed Helm and Kubernetes best practices, load the references:
Read references/helm_best_practices.md
Read references/k8s_best_practices.md
These references include:
  • Chart structure and metadata
  • Template conventions and patterns
  • Values file organization
  • Security best practices
  • Resource limits and requests
  • Common validation issues and fixes
When to load: When validation reveals issues that need context, when implementing new features, or when the user asks about best practices.
有关详细的Helm和Kubernetes最佳实践,请加载以下参考资料:
Read references/helm_best_practices.md
Read references/k8s_best_practices.md
这些参考资料包括:
  • Chart结构和元数据
  • 模板约定和模式
  • 配置值文件组织
  • 安全最佳实践
  • 资源限制和请求
  • 常见验证问题及修复方法
何时加载: 当验证发现需要上下文的问题时,实现新功能时,或用户询问最佳实践时。

Working with Chart Dependencies

处理Chart依赖

When a chart has dependencies (in
Chart.yaml
or
charts/
directory):
  1. Update dependencies:
bash
helm dependency update <chart-directory>
  1. List dependencies:
bash
helm dependency list <chart-directory>
  1. Validate dependencies:
    • Check that dependency versions are available
    • Verify dependency values are properly scoped
    • Test templates with dependency resources
  2. Override dependency values:
yaml
undefined
当Chart存在依赖(在
Chart.yaml
charts/
目录中):
  1. 更新依赖:
bash
helm dependency update <chart-directory>
  1. 列出依赖:
bash
helm dependency list <chart-directory>
  1. 验证依赖:
    • 检查依赖版本是否可用
    • 验证依赖配置值是否正确作用域
    • 测试包含依赖资源的模板
  2. 覆盖依赖配置值:
yaml
undefined

values.yaml

values.yaml

postgresql: enabled: true postgresqlPassword: "secret" persistence: size: 10Gi
undefined
postgresql: enabled: true postgresqlPassword: "secret" persistence: size: 10Gi
undefined

Error Handling Strategies

错误处理策略

Tool Not Available

工具不可用

  • Run
    scripts/setup_tools.sh
    to check availability
  • Provide installation instructions
  • Skip optional stages but document what was skipped
  • Continue with available tools
  • 运行
    scripts/setup_tools.sh
    检查可用性
  • 提供安装说明
  • 跳过可选阶段但记录跳过的内容
  • 使用可用工具继续

Template Rendering Errors

模板渲染错误

  • Show the specific template file and line number
  • Check if values are defined in values.yaml
  • Verify template function syntax
  • Test with simpler value combinations
  • Use
    --debug
    flag for detailed error messages
  • 显示具体的模板文件和行号
  • 检查values.yaml中是否定义了配置值
  • 验证模板函数语法
  • 使用更简单的配置组合测试
  • 使用
    --debug
    参数获取详细错误信息

Cluster Access Issues

集群访问问题

  • Fall back to client-side validation
  • Use rendered templates with kubectl
  • Skip cluster validation if no kubectl config
  • Document limitations in validation report
  • 回退到客户端验证
  • 使用渲染后的模板配合kubectl
  • 如果没有kubectl配置则跳过集群验证
  • 在验证报告中记录限制

CRD Documentation Not Found

CRD文档未找到

  • Document that documentation lookup failed
  • Attempt validation with kubeconform CRD schemas
  • Suggest manual CRD inspection:
    bash
    kubectl get crd <crd-name>.group -o yaml
    kubectl explain <kind>
  • 记录文档查询失败
  • 尝试使用kubeconform CRD Schema进行验证
  • 建议手动检查CRD:
    bash
    kubectl get crd <crd-name>.group -o yaml
    kubectl explain <kind>

Validation Stage Failures

验证阶段失败

  • Continue to next stage even if one fails
  • Collect all errors before presenting to user
  • Prioritize fixing Helm lint errors first
  • Then fix template errors
  • Finally fix schema/validation errors
  • 即使某个阶段失败,继续执行下一阶段
  • 在呈现给用户前收集所有错误
  • 优先修复Helm检查错误
  • 然后修复模板错误
  • 最后修复Schema/验证错误

macOS Extended Attributes Issue

macOS扩展属性问题

Symptom: Helm reports "Chart.yaml file is missing" even though the file exists and is readable.
Cause: On macOS, files created programmatically (via Write tool, scripts, or certain editors) may have extended attributes (e.g.,
com.apple.provenance
,
com.apple.quarantine
) that interfere with Helm's file detection.
Diagnosis:
bash
undefined
症状: Helm报告“缺少Chart.yaml文件”,但文件实际存在且可读。
原因: 在macOS上,通过编程方式创建的文件(例如通过Write工具、脚本或某些编辑器)可能带有扩展属性(如
com.apple.provenance
com.apple.quarantine
),会干扰Helm的文件检测。
诊断:
bash
undefined

Check for extended attributes

检查扩展属性

xattr /path/to/chart/Chart.yaml
xattr /path/to/chart/Chart.yaml

If attributes are present, you'll see output like:

如果存在属性,会显示类似以下的输出:

com.apple.provenance

com.apple.provenance

com.apple.quarantine

com.apple.quarantine


**Solutions:**

1. **Remove extended attributes:**
   ```bash
   # Remove all extended attributes from a file
   xattr -c /path/to/chart/Chart.yaml

   # Remove all extended attributes recursively from chart directory
   xattr -cr /path/to/chart/
  1. Create files using shell commands instead:
    bash
    # Use cat with heredoc instead of direct file writes
    cat > Chart.yaml << 'EOF'
    apiVersion: v2
    name: mychart
    version: 0.1.0
    EOF
  2. Copy from helm-created chart:
    bash
    # Create a fresh chart and copy structure
    helm create temp-chart
    cp -r temp-chart/* /path/to/your/chart/
    rm -rf temp-chart
Prevention: When creating new chart files on macOS, prefer using
helm create
as a base or use shell heredocs (
cat > file << 'EOF'
) rather than direct file creation tools.

**解决方案:**

1. **移除扩展属性:**
   ```bash
   # 移除文件的所有扩展属性
   xattr -c /path/to/chart/Chart.yaml

   # 递归移除Chart目录的所有扩展属性
   xattr -cr /path/to/chart/
  1. 改用Shell命令创建文件:
    bash
    # 使用cat和 heredoc 代替直接写入文件
    cat > Chart.yaml << 'EOF'
    apiVersion: v2
    name: mychart
    version: 0.1.0
    EOF
  2. 从Helm创建的Chart中复制:
    bash
    # 创建一个新的Chart并复制结构
    helm create temp-chart
    cp -r temp-chart/* /path/to/your/chart/
    rm -rf temp-chart
预防: 在macOS上创建新的Chart文件时,优先使用
helm create
作为基础,或使用Shell heredoc(
cat > file << 'EOF'
)而非直接文件创建工具。

Communication Guidelines

沟通指南

When presenting validation results and fixes:
  1. Be clear and concise about what was found
  2. Explain why issues matter (e.g., "This will cause pod creation to fail")
  3. Provide context from Helm best practices when relevant
  4. Group related issues (e.g., all missing helper issues together)
  5. Use file:line references when available
  6. Show confidence level for auto-fixes (high confidence = syntax, low = logic changes)
  7. Always provide a summary after applying fixes including:
    • What was changed and why
    • File and line references for each fix
    • Total count of issues resolved
    • Final validation status
    • Any remaining warnings or recommendations
呈现验证结果和修复建议时:
  1. 清晰简洁地说明发现的问题
  2. 解释问题的影响(例如“这会导致Pod创建失败”)
  3. 提供相关上下文,参考Helm最佳实践
  4. 分组相关问题(例如,所有缺少助手的问题放在一起)
  5. 使用文件:行号引用(如果可用)
  6. 说明自动修复的置信度(高置信度=语法问题,低置信度=逻辑变更)
  7. 应用修复后始终提供总结,包括:
    • 更改的内容和原因
    • 每个修复的文件和行号引用
    • 已解决的问题总数
    • 最终验证状态
    • 任何剩余的警告或建议

Version Awareness

版本兼容性

Always consider Kubernetes and Helm version compatibility:
  • Check for deprecated Kubernetes APIs
  • Ensure Helm chart apiVersion is v2 (for Helm 3+)
  • For CRDs, ensure the apiVersion matches what's in the cluster
  • Use
    kubectl api-versions
    to list available API versions
  • Reference version-specific documentation when available
  • Set
    kubeVersion
    constraint in Chart.yaml if needed
始终考虑Kubernetes和Helm的版本兼容性:
  • 检查已弃用的Kubernetes API
  • 确保Helm Chart的apiVersion为v2(适用于Helm 3+)
  • 对于CRD,确保apiVersion与集群中的版本匹配
  • 使用
    kubectl api-versions
    列出可用的API版本
  • 参考特定版本的文档
  • 如果需要,在Chart.yaml中设置
    kubeVersion
    约束

Chart Testing

Chart测试

For comprehensive testing, use Helm test resources:
  1. Create test resources:
yaml
undefined
如需全面测试,使用Helm测试资源:
  1. 创建测试资源:
yaml
undefined

templates/tests/test-connection.yaml

templates/tests/test-connection.yaml

apiVersion: v1 kind: Pod metadata: name: "{{ include "mychart.fullname" . }}-test-connection" annotations: "helm.sh/hook": test spec: containers: - name: wget image: busybox command: ['wget'] args: ['{{ include "mychart.fullname" . }}:{{ .Values.service.port }}'] restartPolicy: Never

2. **Run tests:**
```bash
helm test <release-name>
apiVersion: v1 kind: Pod metadata: name: "{{ include "mychart.fullname" . }}-test-connection" annotations: "helm.sh/hook": test spec: containers: - name: wget image: busybox command: ['wget'] args: ['{{ include "mychart.fullname" . }}:{{ .Values.service.port }}'] restartPolicy: Never

2. **运行测试:**
```bash
helm test <release-name>

Automation Opportunities Reference

自动化机会参考

During Stage 10 (Final Report), list all detected automation opportunities in the summary.
Do NOT ask user questions or modify files. Simply list recommendations.
Automation opportunities to detect and list:
Missing ItemRecommendation
_helpers.tpl
Run:
bash scripts/generate_helpers.sh <chart>
.helmignore
Copy from:
assets/.helmignore
values.schema.json
Copy and customize from:
assets/values.schema.json
NOTES.txt
Create post-install notes template
README.md
Create chart documentation
Repeated patternsExtract to helper functions
Security recommendations to include when issues found:
IssueRecommendation
Missing pod securityContextAdd
runAsNonRoot: true
,
runAsUser: 1000
,
fsGroup: 2000
Missing container securityContextAdd
allowPrivilegeEscalation: false
,
readOnlyRootFilesystem: true
,
capabilities.drop: [ALL]
Missing resource limitsAdd CPU/memory limits and requests
Using
:latest
tag
Pin to specific image version
Missing probesAdd liveness and readiness probes
Template improvement recommendations:
IssueRecommendation
Using
template
instead of
include
Replace with
include
for pipeline support
Missing
nindent
Add
nindent
for proper YAML indentation
No default valuesAdd
default
function for optional values
Missing
required
function
Add
required
for critical values
在阶段10(最终报告)中,在总结中列出所有检测到的自动化机会。
不要询问用户问题或修改文件,只需列出建议。
需要检测并列出的自动化机会:
缺失项建议
_helpers.tpl
运行:
bash scripts/generate_helpers.sh <chart>
.helmignore
assets/.helmignore
复制
values.schema.json
assets/values.schema.json
复制并自定义
NOTES.txt
创建安装后说明模板
README.md
创建Chart文档
重复模式提取为助手函数
发现问题时的安全建议:
问题建议
缺少Pod securityContext添加
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
缺少容器securityContext添加
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities.drop: [ALL]
缺少资源限制添加CPU/内存限制和请求
使用
:latest
标签
固定到特定镜像版本
缺少探针添加存活和就绪探针
模板改进建议:
问题建议
使用
template
而非
include
替换为
include
以支持管道
缺少
nindent
添加
nindent
以确保正确的YAML缩进
没有默认值为可选值添加
default
函数
缺少
required
函数
为关键值添加
required

Resources

资源

scripts/

scripts/

setup_tools.sh
  • Checks for required validation tools (helm, yamllint, kubeconform, kubectl)
  • Provides installation instructions for missing tools
  • Verifies versions of installed tools
  • Usage:
    bash scripts/setup_tools.sh
validate_chart_structure.sh
  • Validates Helm chart directory structure
  • Checks for required files (Chart.yaml, values.yaml, templates/)
  • Verifies file formats and syntax
  • Usage:
    bash scripts/validate_chart_structure.sh <chart-directory>
detect_crd_wrapper.sh
  • Wrapper script that handles Python dependency management
  • Automatically creates temporary venv if PyYAML is not available
  • Calls detect_crd.py to parse YAML files
  • Usage:
    bash scripts/detect_crd_wrapper.sh <file.yaml>
detect_crd.py
  • Parses YAML files to identify Custom Resource Definitions
  • Extracts kind, apiVersion, group, and version information
  • Outputs JSON for programmatic processing
  • Requires PyYAML (handled automatically by wrapper script)
  • Can be called directly:
    python3 scripts/detect_crd.py <file.yaml>
generate_helpers.sh
  • Generates standard Helm helpers (_helpers.tpl) for a chart
  • Creates fullname, labels, and selector helpers
  • Usage:
    bash scripts/generate_helpers.sh <chart-directory>
setup_tools.sh
  • 检查所需的验证工具(helm、yamllint、kubeconform、kubectl)
  • 为缺失的工具提供安装说明
  • 验证已安装工具的版本
  • 用法:
    bash scripts/setup_tools.sh
validate_chart_structure.sh
  • 验证Helm Chart目录结构
  • 检查必填文件(Chart.yaml、values.yaml、templates/)
  • 验证文件格式和语法
  • 用法:
    bash scripts/validate_chart_structure.sh <chart-directory>
detect_crd_wrapper.sh
  • 处理Python依赖管理的包装脚本
  • 如果PyYAML不可用,自动创建临时虚拟环境
  • 调用detect_crd.py解析YAML文件
  • 用法:
    bash scripts/detect_crd_wrapper.sh <file.yaml>
detect_crd.py
  • 解析YAML文件以识别Custom Resource Definitions
  • 提取kind、apiVersion、group和version信息
  • 输出JSON以支持程序化处理
  • 需要PyYAML(由包装脚本自动处理)
  • 可直接调用:
    python3 scripts/detect_crd.py <file.yaml>
generate_helpers.sh
  • 为Chart生成标准Helm助手(_helpers.tpl)
  • 创建全名、标签和选择器助手
  • 用法:
    bash scripts/generate_helpers.sh <chart-directory>

references/

references/

helm_best_practices.md
  • Comprehensive guide to Helm chart best practices
  • Covers template patterns, helper functions, values structure
  • Common validation issues and how to fix them
  • Security and performance recommendations
  • Load when providing context for Helm-specific issues
k8s_best_practices.md
  • Comprehensive guide to Kubernetes YAML best practices
  • Covers metadata, labels, resource limits, security context
  • Common validation issues and how to fix them
  • Load when providing context for Kubernetes-specific issues
template_functions.md
  • Reference guide for Helm template functions
  • Examples of all built-in functions
  • Sprig function library reference
  • Custom function patterns
  • Load when implementing complex templates
helm_best_practices.md
  • Helm Chart最佳实践综合指南
  • 涵盖模板模式、助手函数、配置值结构
  • 常见验证问题及修复方法
  • 安全和性能建议
  • 处理Helm特定问题时加载
k8s_best_practices.md
  • Kubernetes YAML最佳实践综合指南
  • 涵盖元数据、标签、资源限制、安全上下文
  • 常见验证问题及修复方法
  • 处理Kubernetes特定问题时加载
template_functions.md
  • Helm模板函数参考指南
  • 所有内置函数的示例
  • Sprig函数库参考

assets/

assets/

.helmignore
  • Standard .helmignore file for excluding files from packaging
  • Pre-configured with common patterns
.yamllint
  • Pre-configured yamllint rules for Kubernetes YAML
  • Follows Kubernetes conventions (2-space indentation, line length, etc.)
  • Can be customized per project
  • Usage:
    yamllint -c assets/.yamllint <file.yaml>
values.schema.json
  • Example JSON Schema for values validation
  • Can be copied and customized for specific charts
  • Provides type safety and validation
.helmignore
  • 用于排除打包文件的标准.helmignore文件
  • 预配置了常见模式
.yamllint
  • 针对Kubernetes YAML的预配置yamllint规则
  • 遵循Kubernetes约定(2空格缩进、行长度等)
  • 可根据项目自定义
  • 用法:
    yamllint -c assets/.yamllint <file.yaml>
values.schema.json
  • 配置值验证的示例JSON Schema
  • 可复制并针对特定Chart自定义
  • 提供类型安全和验证功能