yaml-validator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

YAML Validator

YAML 验证工具

Validate and fix YAML syntax and structure for all YAML files in the project.
验证并修复项目中所有YAML文件的语法与结构。

Purpose

用途

Ensures YAML files follow proper syntax, have valid structure, and comply with schema requirements where applicable.
确保YAML文件遵循正确语法、具备有效结构,并在适用情况下符合 schema 要求。

When to Use

适用场景

  • Creating new YAML configuration files
  • Editing existing .yml/.yaml files
  • Debugging YAML syntax errors
  • Validating GitHub Actions workflows
  • Checking docker-compose files
  • Validating Kubernetes manifests
  • Pre-commit YAML quality checks
  • CI/CD configuration validation
  • 创建新的YAML配置文件时
  • 编辑现有.yml/.yaml文件时
  • 调试YAML语法错误时
  • 验证GitHub Actions工作流时
  • 检查docker-compose文件时
  • 验证Kubernetes清单时
  • 提交前的YAML质量检查时
  • CI/CD配置验证时

YAML Syntax Rules

YAML 语法规则

Basic Structure

基础结构

yaml
undefined
yaml
undefined

Comments start with

注释以#开头

key: value # Simple key-value list: # Lists use dash prefix
  • item1
  • item2 nested: # Nested objects key1: value1 key2: value2 multiline: | # Literal block scalar Line 1 Line 2 flow: > # Folded block scalar This is a long sentence that folds
undefined
key: value # 简单键值对 list: # 列表使用短横线前缀
  • item1
  • item2 nested: # 嵌套对象 key1: value1 key2: value2 multiline: | # 字面量块标量 Line 1 Line 2 flow: > # 折叠块标量 This is a long sentence that folds
undefined

Data Types

数据类型

yaml
string: "value"               # Quoted string
unquoted: value               # Unquoted string
number: 42                    # Integer
float: 3.14                   # Float
boolean: true                 # Boolean (true/false, yes/no, on/off)
null_value: null              # Null
empty: ~                      # Also null
multiline_string: |
  This preserves
  newlines
yaml
string: "value"               # 带引号的字符串
unquoted: value               # 无引号字符串
number: 42                    # 整数
float: 3.14                   # 浮点数
boolean: true                 # 布尔值(true/false、yes/no、on/off)
null_value: null              # 空值
empty: ~                      # 同样表示空值
multiline_string: |
  This preserves
  newlines

Indentation Rules

缩进规则

  • Use 2 spaces per indentation level (not tabs)
  • Consistent indentation throughout file
  • Keys at same level must align
  • Lists use 2 additional spaces after dash
yaml
undefined
  • 每个缩进层级使用2个空格(禁止使用制表符)
  • 文件内保持缩进一致
  • 同一层级的键必须对齐
  • 列表项在短横线后额外添加2个空格
yaml
undefined

Correct

正确示例

parent: child: value list: - item1 - item2
parent: child: value list: - item1 - item2

Incorrect - mixed tabs/spaces

错误示例 - 混合使用制表符与空格

parent: child: value # Tab character!
parent: child: value # 制表符!

Incorrect - wrong indentation

错误示例 - 缩进层级错误

parent: child: value # Only 1 space
undefined
parent: child: value # 仅1个空格
undefined

Common Issues and Fixes

常见问题与修复方案

Issue 1: Invalid Indentation

问题1:无效缩进

Problem: Mixed spaces and tabs or wrong indentation level Fix: Convert all to 2-space indentation
yaml
undefined
问题描述: 混合使用空格与制表符,或缩进层级错误 修复方案: 统一转换为2个空格缩进
yaml
undefined

Wrong

错误示例

parent: child: value
parent: child: value

Correct

正确示例

parent: child: value
undefined
parent: child: value
undefined

Issue 2: Missing Colon

问题2:缺失冒号

Problem: Key without colon separator Fix: Add colon and space after key
yaml
undefined
问题描述: 键后未添加冒号分隔符 修复方案: 在键后添加冒号与空格
yaml
undefined

Wrong

错误示例

key value
key value

Correct

正确示例

key: value
undefined
key: value
undefined

Issue 3: Special Characters in Strings

问题3:字符串包含特殊字符

Problem: Characters like
:
,
{
,
}
,
[
,
]
in unquoted strings Fix: Quote strings containing special characters
yaml
undefined
问题描述: 无引号字符串中包含
:
,
{
,
}
,
[
,
]
等特殊字符 修复方案: 对包含特殊字符的字符串添加引号
yaml
undefined

Wrong

错误示例

message: Error: something went wrong
message: Error: something went wrong

Correct

正确示例

message: "Error: something went wrong"
undefined
message: "Error: something went wrong"
undefined

Issue 4: Duplicate Keys

问题4:重复键

Problem: Same key defined multiple times Fix: Remove duplicate or merge values
yaml
undefined
问题描述: 同一键被多次定义 修复方案: 删除重复键或合并值
yaml
undefined

Wrong

错误示例

config: key: value1 key: value2
config: key: value1 key: value2

Correct

正确示例

config: key: value1 other_key: value2
undefined
config: key: value1 other_key: value2
undefined

Issue 5: Unquoted Strings That Look Like Types

问题5:形似类型的无引号字符串

Problem:
yes
,
no
,
on
,
off
,
true
,
false
, numbers Fix: Quote strings that should be literal text
yaml
undefined
问题描述: 字符串内容为
yes
no
on
off
true
false
或数字,会被解析为对应类型 修复方案: 对需要作为文本字面量的字符串添加引号
yaml
undefined

Wrong - parsed as boolean true

错误示例 - 会被解析为布尔值true

country: YES
country: YES

Correct

正确示例

country: "YES"
undefined
country: "YES"
undefined

Issue 6: Trailing Spaces

问题6:行尾空格

Problem: Spaces at end of lines Fix: Remove trailing whitespace
问题描述: 行末尾存在空格 修复方案: 删除行尾空白字符

Issue 7: Missing Document Start

问题7:缺失文档起始标记

Problem: File doesn't start with
---
Fix: Optional but recommended for clarity
yaml
---
问题描述: 文件未以
---
开头 修复方案: 可选但推荐添加以提升可读性
yaml
---

Your content here

内容从这里开始

undefined
undefined

File-Specific Validation

特定文件验证

GitHub Actions Workflows (
.github/workflows/*.yml
)

GitHub Actions 工作流(
.github/workflows/*.yml

Required structure:
yaml
name: Workflow Name
on: [push, pull_request]        # Event triggers
jobs:
  job-name:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Step name
        run: echo "Hello"
Common issues:
  • Missing
    on:
    trigger
  • Invalid
    runs-on
    value
  • Missing
    steps:
  • Old action versions (v1/v2)
必填结构:
yaml
name: Workflow Name
on: [push, pull_request]        # 事件触发器
jobs:
  job-name:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Step name
        run: echo "Hello"
常见问题:
  • 缺失
    on:
    触发器
  • runs-on
    值无效
  • 缺失
    steps:
  • 使用旧版Action(v1/v2)

Docker Compose (
docker-compose.yml
)

Docker Compose(
docker-compose.yml

yaml
version: "3.8"
services:
  app:
    image: node:18
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
Common issues:
  • Missing version declaration
  • Port binding format
  • Volume mount syntax
yaml
version: "3.8"
services:
  app:
    image: node:18
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
常见问题:
  • 缺失版本声明
  • 端口绑定格式错误
  • 卷挂载语法错误

Kubernetes Manifests (
*.yaml
)

Kubernetes 清单(
*.yaml

yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: container-name
      image: nginx:latest
Common issues:
  • Wrong apiVersion
  • Missing required fields (apiVersion, kind, metadata, spec)
  • List indentation under containers
yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: container-name
      image: nginx:latest
常见问题:
  • apiVersion 错误
  • 缺失必填字段(apiVersion、kind、metadata、spec)
  • containers下的列表缩进错误

Workflow

验证流程

1. Parse YAML File

1. 解析YAML文件

bash
undefined
bash
undefined

Basic syntax check

基础语法检查

python3 -c "import yaml; yaml.safe_load(open('file.yml'))"
python3 -c "import yaml; yaml.safe_load(open('file.yml'))"

With better error messages

带更友好的错误提示

python3 -c " import yaml try: with open('file.yml') as f: yaml.safe_load(f) print('✓ Valid YAML') except yaml.YAMLError as e: print(f'✗ Error: {e}') "
undefined
python3 -c " import yaml try: with open('file.yml') as f: yaml.safe_load(f) print('✓ 有效的YAML') except yaml.YAMLError as e: print(f'✗ 错误:{e}') "
undefined

2. Validate Structure

2. 验证结构

Check for:
  • Valid YAML syntax
  • Consistent indentation (2 spaces)
  • No trailing spaces
  • No tabs (spaces only)
  • Proper key-value formatting
  • Valid data types
  • No duplicate keys
检查以下项:
  • 有效的YAML语法
  • 一致的缩进(2个空格)
  • 无行尾空格
  • 无制表符(仅使用空格)
  • 正确的键值格式
  • 有效的数据类型
  • 无重复键

3. File-Specific Checks

3. 特定文件检查

Based on file location and purpose:
  • GitHub Actions: Valid triggers, job structure
  • Docker Compose: Version, service definitions
  • K8s manifests: apiVersion, required fields
  • Config files: Expected schema
根据文件位置与用途:
  • GitHub Actions:验证触发器、任务结构
  • Docker Compose:验证版本、服务定义
  • K8s清单:验证apiVersion、必填字段
  • 配置文件:验证预期schema

4. Report Issues

4. 问题报告

For each violation:
  • Line number and column
  • Issue type: Error / Warning / Info
  • Description of the problem
  • Suggested fix with code example
针对每个违规项:
  • 行号与列号
  • 问题类型:错误 / 警告 / 信息
  • 问题描述
  • 带代码示例的修复建议

Validation Commands

验证命令

bash
undefined
bash
undefined

Install yamllint (recommended)

安装yamllint(推荐)

pip install yamllint
pip install yamllint

Validate single file

验证单个文件

yamllint file.yml
yamllint file.yml

Validate with config

使用配置文件验证

yamllint -c .yamllint file.yml
yamllint -c .yamllint file.yml

Check all YAML files

检查所有YAML文件

find . -name ".yml" -o -name ".yaml" | xargs yamllint
find . -name ".yml" -o -name ".yaml" | xargs yamllint

Using Python (if yamllint not available)

使用Python验证(若yamllint不可用)

python3 -c " import yaml import sys errors = [] for file in sys.argv[1:]: try: with open(file) as f: yaml.safe_load(f) print(f'✓ {file}') except Exception as e: errors.append(f'✗ {file}: {e}') print(f'✗ {file}: {e}') sys.exit(1 if errors else 0) " file1.yml file2.yml
undefined
python3 -c " import yaml import sys errors = [] for file in sys.argv[1:]: try: with open(file) as f: yaml.safe_load(f) print(f'✓ {file}') except Exception as e: errors.append(f'✗ {file}: {e}') print(f'✗ {file}: {e}') sys.exit(1 if errors else 0) " file1.yml file2.yml
undefined

yamllint Configuration

yamllint 配置

Create
.yamllint
in project root:
yaml
---
yaml-files:
  - '*.yml'
  - '*.yaml'

rules:
  braces:
    min-spaces-inside: 0
    max-spaces-inside: 0
  brackets:
    min-spaces-inside: 0
    max-spaces-inside: 0
  colons:
    max-spaces-after: 1
    max-spaces-before: 0
  commas:
    max-spaces-after: 1
    max-spaces-before: 0
  comments:
    min-spaces-from-content: 1
    require-starting-space: true
  comments-indentation: disable
  document-end: disable
  document-start: disable
  empty-lines:
    max: 2
  empty-values: disable
  indentation:
    spaces: 2
    indent-sequences: true
    check-multi-line-strings: false
  key-duplicates: enable
  key-ordering: disable
  line-length:
    max: 120
  new-line-at-end-of-file: enable
  new-lines:
    type: unix
  octal-values: disable
  quoted-strings: disable
  trailing-spaces: enable
  truthy: disable
在项目根目录创建
.yamllint
文件:
yaml
---
yaml-files:
  - '*.yml'
  - '*.yaml'

rules:
  braces:
    min-spaces-inside: 0
    max-spaces-inside: 0
  brackets:
    min-spaces-inside: 0
    max-spaces-inside: 0
  colons:
    max-spaces-after: 1
    max-spaces-before: 0
  commas:
    max-spaces-after: 1
    max-spaces-before: 0
  comments:
    min-spaces-from-content: 1
    require-starting-space: true
  comments-indentation: disable
  document-end: disable
  document-start: disable
  empty-lines:
    max: 2
  empty-values: disable
  indentation:
    spaces: 2
    indent-sequences: true
    check-multi-line-strings: false
  key-duplicates: enable
  key-ordering: disable
  line-length:
    max: 120
  new-line-at-end-of-file: enable
  new-lines:
    type: unix
  octal-values: disable
  quoted-strings: disable
  trailing-spaces: enable
  truthy: disable

Output Format

输出格式

undefined
undefined

YAML Validation Report

YAML验证报告

Summary

摘要

  • Files Checked: 5
  • Errors: 2
  • Warnings: 3
  • Status: FAIL
  • 检查文件数:5
  • 错误数:2
  • 警告数:3
  • 状态:失败

file1.yml

file1.yml

✓ Valid YAML syntax ⚠ Warning (Line 15): Line too long (145 > 120)
✓ 有效的YAML语法 ⚠ 警告(第15行):行过长(145 > 120)

file2.yml

file2.yml

✗ Error (Line 8, Col 5): Invalid indentation Current: 4 spaces Expected: 2 spaces ✗ Error (Line 12): Duplicate key "name"
✗ 错误(第8行,第5列):无效缩进 当前:4个空格 预期:2个空格 ✗ 错误(第12行):重复键"name"

file3.yml

file3.yml

✓ Valid YAML syntax ⚠ Warning (Line 20): Trailing spaces
undefined
✓ 有效的YAML语法 ⚠ 警告(第20行):行尾空格
undefined

Best Practices

最佳实践

DO

建议做法

✓ Use 2 spaces for indentation ✓ Quote strings with special characters (:, {, }, [, ]) ✓ Use consistent formatting throughout ✓ Validate before committing ✓ Add comments for complex sections ✓ Keep lines under 120 characters ✓ End files with newline ✓ Use
---
document start marker for clarity
✓ 使用2个空格进行缩进 ✓ 对包含特殊字符的字符串添加引号(:、{、}、[、]) ✓ 全程保持格式一致 ✓ 提交前进行验证 ✓ 为复杂部分添加注释 ✓ 行长度控制在120字符以内 ✓ 文件末尾添加换行符 ✓ 使用
---
文档起始标记提升可读性

DON'T

禁止做法

✗ Use tabs for indentation ✗ Leave trailing spaces ✗ Mix quoted/unquoted styles inconsistently ✗ Use duplicate keys ✗ Forget to quote strings that look like booleans/numbers ✗ Mix YAML 1.1 and 1.2 features
✗ 使用制表符进行缩进 ✗ 保留行尾空格 ✗ 不一致地混合使用带引号/无引号风格 ✗ 使用重复键 ✗ 未对形似布尔值/数字的字符串添加引号 ✗ 混合使用YAML 1.1与1.2特性

Examples

示例

Valid GitHub Actions

有效的GitHub Actions配置

yaml
---
name: Rust CI
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run tests
        run: cargo test --all
yaml
---
name: Rust CI
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: 运行测试
        run: cargo test --all

Valid Docker Compose

有效的Docker Compose配置

yaml
---
version: "3.8"

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
    depends_on:
      - db

  db:
    image: postgres:15
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
yaml
---
version: "3.8"

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: production
    depends_on:
      - db

  db:
    image: postgres:15
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Valid Kubernetes

有效的Kubernetes配置

yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-deployment
  labels:
    app: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:alpine
          ports:
            - containerPort: 80
yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-deployment
  labels:
    app: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:alpine
          ports:
            - containerPort: 80

Integration

集成场景

Use with:
  • github-workflows: Validate workflow files
  • code-quality: Pre-commit YAML checks
  • debug-troubleshoot: Debug parsing errors
  • feature-implement: Create new config files
可与以下场景集成:
  • github-workflows:验证工作流文件
  • code-quality:提交前的YAML质量检查
  • debug-troubleshoot:调试解析错误
  • feature-implement:创建新配置文件

Quick Fixes

快速修复命令

bash
undefined
bash
undefined

Fix trailing spaces

修复行尾空格

sed -i 's/[[:space:]]*$//' file.yml
sed -i 's/[[:space:]]*$//' file.yml

Convert tabs to spaces

将制表符转换为空格

sed -i 's/\t/ /g' file.yml
sed -i 's/\t/ /g' file.yml

Ensure newline at end

确保文件末尾有换行符

sed -i -e '$a' file.yml
undefined
sed -i -e '$a' file.yml
undefined