YAML 格式

精选 YAML 格式 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#入门指南

#简介 (Introduction)

YAML 是一种面向人类可读可写的数据序列化语言

  • YAML does not allow the use of tabs
  • Must be space between the element parts
  • YAML is CASE sensitive
  • End your YAML file with the .yaml or .yml extension
  • YAML is a superset of JSON
  • Ansible playbooks are YAML files

#Scalar types

n1: 1            # integer
n2: 1.234        # float

s1: 'abc'        # string
s2: "abc"        # string
s3: abc          # string

b: false         # boolean type

d: 2015-04-05    # date type

#↓ Equivalent JSON

{
  "n1": 1,
  "n2": 1.234,
  "s1": "abc",
  "s2": "abc",
  "s3": "abc",
  "b": false,
  "d": "2015-04-05"
}

Use spaces to indent. There must be space between the element parts.

#变量声明 (Variables)

some_thing: &VAR_NAME foobar
other_thing: *VAR_NAME

#↓ Equivalent JSON

{
  "some_thing": "foobar",
  "other_thing": "foobar"
}

#代码注释 (Comments)

# A single line comment example

# block level comment example
# comment line 1
# comment line 2
# comment line 3

#Multiline strings

description: |
  hello
  world

#↓ Equivalent JSON

{ "description": "hello\nworld\n" }

#Inheritance

parent: &defaults
  a: 2
  b: 3

child:
  <<: *defaults
  b: 4

#↓ Equivalent JSON

{
  "parent": {
    "a": 2,
    "b": 3
  },
  "child": {
    "a": 2,
    "b": 4
  }
}

#Reference

values: &ref
  - Will be
  - reused below

other_values:
  i_am_ref: *ref

#↓ Equivalent JSON

{
  "values": [
    "Will be",
    "reused below"
  ],
  "other_values": {
    "i_am_ref": [
      "Will be",
      "reused below"
    ]
  }
}

#Folded strings

description: >
  hello world

#↓ Equivalent JSON

{ "description": "hello world\n" }

#Two Documents

---
document: this is doc 1
---
document: this is doc 2

YAML uses --- to separate directives from document content.

#document: this is doc 1

document: this is doc 2


YAML 使用 `---` 符号分隔同一个文件内的多个文档内容。

## YAML 集合类型 (YAML Collections)

### 列表/序列 (Sequence)

```yaml
- Mark McGwire
- Sammy Sosa
- Ken Griffey

↓ 等价的 JSON 输出

[
  "Mark McGwire",
  "Sammy Sosa",
  "Ken Griffey"
]

#字典/映射 (Mapping)

hr:  65       # 本垒打
avg: 0.278    # 打击率
rbi: 147      # 打点数

↓ 等价的 JSON 输出

{
  "hr": 65,
  "avg": 0.278,
  "rbi": 147
}

#映射嵌入序列 (Mapping to Sequences)

attributes:
  - a1
  - a2
methods: [getter, setter]

↓ 等价的 JSON 输出

{
  "attributes": ["a1", "a2"],
  "methods": ["getter", "setter"]
}

#序列嵌入映射 (Sequence of Mappings)

children:
  - name: Jimmy Smith
    age: 15
  - name: Jimmy Smith
    age: 15
  -
    name: Sammy Sosa
    age: 12

↓ 等价的 JSON 输出

{
  "children": [
    {"name": "Jimmy Smith", "age": 15},
    {"name": "Jimmy Smith", "age": 15},
    {"name": "Sammy Sosa", "age": 12}
  ]
}

#多维序列 (Sequence of Sequences)

my_sequences:
  - [1, 2, 3]
  - [4, 5, 6]
  -
    - 7
    - 8
    - 9
    - 0 

↓ 等价的 JSON 输出

{
  "my_sequences": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9, 0]
  ]
}

#嵌套映射 (Mapping of Mappings)

Mark McGwire: { hr: 65, avg: 0.278 }
Sammy Sosa: { hr: 63, avg: 0.288 }

↓ 等价的 JSON 输出

{
  "Mark McGwire": {
    "hr": 65,
    "avg": 0.278
  },
  "Sammy Sosa": {
    "hr": 63,
    "avg": 0.288
  }
}

#复杂嵌套集合 (Nested Collections)

Jack:
  id: 1
  name: Franc
  salary: 25000
  hobby:
    - a
    - b
  location: { country: 'A', city: 'A-A' }

↓ 等价的 JSON 输出

{
  "Jack": {
    "id": 1,
    "name": "Franc",
    "salary": 25000,
    "hobby": ["a", "b"],
    "location": {
      "country": "A",
      "city": "A-A"
    }
  }
}

#无序集合 (Unordered Sets)

set1: !!set
  ? one
  ? two
set2: !!set { 'one', 'two' }

↓ 等价的 JSON 输出

{
  "set1": { "one": null, "two": null },
  "set2": { "one": null, "two": null }
}

无序集合 (Set) 被表示为键关联了 null 值的映射字典。

#有序字典映射 (Ordered Mappings)

ordered: !!omap
  - Mark McGwire: 65
  - Sammy Sosa: 63
  - Ken Griffy: 58

↓ 等价的 JSON 输出

{
  "ordered": [
    { "Mark McGwire": 65 },
    { "Sammy Sosa": 63 },
    { "Ken Griffy": 58 }
  ]
}

#YAML 语法参考手册 (YAML Reference)

#术语对应 (Terms)

  • 序列 (Sequence) 即数组 (array) 或列表 (list)
  • 标量 (Scalar) 即字符串 (string) 或数字 (number)
  • 映射 (Mapping) 即哈希 (hash) 或字典 (dictionary)

参考自 YAML.org 官方参考卡片

#文档标记符号 (Document indicators)

符号 描述说明
% 指令标记符 (Directive indicator)
--- 文档起始头标记 (Document header)
... 文档结束标记 (Document terminator)

#集合标记符号 (Collection indicators)

符号 描述说明
? 键标记符 (Key indicator)
: 值标记符 (Value indicator)
- 嵌套序列元素标记符
, 内联分支元素分隔符
[] 包裹内联序列分支
{} 包裹内联键值字典分支

#别名与锚点标记 (Alias indicators)

符号 描述说明
& 锚点定义属性 (Anchor property)
* 别名引用标记 (Alias indicator)

#特殊键标记 (Special keys)

符号 描述说明
= 默认 "value" 映射键
<< 从另一个映射合并所有键值 (Merge)

#标量文本标记 (Scalar indicators)

符号 描述说明
'' 单引号包裹内联未转义标量
" 双引号包裹内联转义标量
| 保留换行的块级标量标记符
> 折叠换行的标量标记符
- 裁切换行修饰符 (|->-)
+ 保留末尾换行修饰符 (|+>+)
1-9 显式缩进层级修饰符 (|1>2),修饰符可组合 (|2-, >+1)

#标签属性 Tag Property (通常隐式推导)

标签语法 描述说明
none 未指定标签(由应用程序自动推导)
! 非特定标签(默认按 !!map/!!seq/!!str 解析)
!foo 主标签(按约自定义的本地 !foo 标签)
!!foo 官方规范二级标签(即 tag:yaml.org,2002:foo
!h!foo 需提前定义 %TAG !h! <prefix>(解析为 <prefix>foo
!<foo> 逐字标签(严格解析为 foo

#杂项标记符号

符号 描述说明
# 注释标记符
`@ 保留供未来版本扩展使用

#核心数据类型 (Core types)

核心标签 数据结构对应
!!map {哈希表、字典、映射}
!!seq {列表、数组、元组、向量、序列}
!!str Unicode 文本字符串

#转义字符 (Escape Codes)

数值编码转义

  • \x12 (8 位 hex)
  • \u1234 (16 位 hex)
  • \U00102030 (32 位 hex)

特殊字符转义

  • \\ (反斜杠 \)
  • \" (双引号 ")
  • \ (空格)
  • \<TAB> (制表符 TAB)

C 语言传统转义

  • \0 (空字符 NUL)
  • \a (响铃 BEL)
  • \b (退格 BS)
  • \f (换页 FF)
  • \n (换行 LF)
  • \r (回车 CR)
  • \t (制表符 TAB)
  • \v (垂直制表符 VTAB)

补充转义字符

  • \e (Escape ESC)
  • \_ (不换行空格 NBSP)
  • \N (下一行 NEL)
  • \L (行分隔符 LS)
  • \P (段落分隔符 PS)

#扩展集合类型 (More types)

扩展标签 示例对应
!!set {cherries, plums, apples}
!!omap [one: 1, two: 2]

#跨语言独立标量类型 (Language Independent Scalar Types)

表达式类型 对应具体含义
{~, null} Null 空值 (无值)
[1234, 0x4D2, 02333] [十进制整数, 十六进制整数, 八进制整数]
[1_230.15, 12.3015e+02] [定点浮点数, 科学计数法浮点数]
[.inf, -.Inf, .NAN] [正无穷大, 负无穷大, 非数字 NaN]
{Y, true, Yes, ON} 布尔真 (Boolean true)
{n, FALSE, No, off} 布尔假 (Boolean false)

#🔗 参考资源