语法
基本规则
Indentation只用空格(不用 tab),缩进深度须一致
#注释(到行尾)
---文档开始标记
...文档结束标记
Case sensitive键和值区分大小写
最小示例
--- name: Alice age: 30 active: true
标量
标量类型
hello字符串(无引号)
"hello"字符串(双引号,支持转义)
'hello'字符串(单引号,字面值)
42 / 3.14数字(整数/浮点数)
true / false布尔值
null / ~空值
2026-03-26日期(ISO 8601)
引号规则
plain: no quotes needed special: "colon: and hash # need quotes" escape: "line\nnewline" literal: 'no \n escaping here'
序列
块序列
fruits: - apple - banana - cherry
流序列(内联)
colors: [red, green, blue] matrix: [[1, 2], [3, 4]]
对象序列
users: - name: Alice role: admin - name: Bob role: user
映射
块映射
server: host: localhost port: 8080 debug: false
流映射(内联)
point: {x: 10, y: 20}
复合键
? [first, second] : "compound key value"
锚点与别名
定义与复用
defaults: &defaults timeout: 30 retries: 3 production: <<: *defaults timeout: 60
参考
&name定义锚点
*name引用(别名)锚点
<<合并键 — 将映射合并到当前
多行字符串
块标量
| (literal)保留换行符
> (folded)将换行折叠为空格
|+ (keep)字面值,保留末尾换行
|- (strip)字面值,去除末尾换行
>- (fold+strip)折叠,去除末尾换行
字面块
script: | echo "line one" echo "line two"
折叠块
description: > This long text will be folded into a single line with spaces.
类型标签
类型标签
!!str 42强制为字符串 "42"
!!int "42"强制为整数 42
!!float 1强制为浮点数 1.0
!!bool "true"强制为布尔值
!!null ""强制为空值
!!binaryBase64 编码的二进制数据
标签示例
port: !!str 8080 enabled: !!bool "yes" version: !!float 3
常用模式
Docker Compose
services: web: image: nginx:alpine ports: ["80:80"] environment: NODE_ENV: production
GitHub Actions
on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
技巧
yamllintYAML 语法与风格检查工具
yq命令行 YAML 处理器(类似 jq)
Avoid NorwayNO 会被解析为布尔 false — 国家代码需加引号
Avoid !!python不要用不安全的 loader 加载不可信的 YAML