YAML格式笔记
·
YAML 的全称是 “YAML Ain’t Markup Language”(递归缩写),强调它是以数据为中心,不像 XML 那样以文档标记为中心。
设计目标是:人性化、可读性高、易于编写,适合做配置文件和数据序列化。
核心特点
- 使用缩进表示层级关系:类似于 Python,不能使用制表符(Tab),只使用空格(通常为 2 或 4 个)进行缩进。缩进相同的元素属于同一层级。
- 大小写敏感:
key和KEY是不同的。 - 使用
#表示注释:从#开始到行尾的内容都会被解析器忽略。 - 支持三种基本数据结构:
- 对象(Maps / Dictionaries):键值对集合。
- 数组(Lists / Sequences):一组按顺序排列的值。
- 标量(Scalars):单个的、不可再分的值,如字符串、布尔值、整数、浮点数、Null 等。
基本语法详解
1. 对象(Maps / Dictionaries)
表示键值对,使用冒号 : 加空格来分隔键和值。
# 简单的键值对
name: John Doe
age: 30
is_student: false
# 多行对象(嵌套)
person:
name: Alice
address:
city: Beijing
street: Zhongguancun
hobbies:
- reading
- hiking
等价于 JSON:
{
"name": "John Doe",
"age": 30,
"is_student": false,
"person": {
"name": "Alice",
"address": {
"city": "Beijing",
"street": "Zhongguancun"
},
"hobbies": ["reading", "hiking"]
}
}
流式风格(Flow style):使用花括号 {} 可以写成类似 JSON 的紧凑格式,常用于单行表示。
person: { name: Alice, age: 25 }
2. 数组(Lists / Sequences)
使用短横线 - 加空格开头表示数组的一项。
# 简单数组
fruits:
- Apple
- Banana
- Orange
# 数组内包含对象
employees:
- name: John
job: Developer
- name: Jane
job: Designer
# 内联数组(流式风格)
colors: [red, blue, green]
等价于 JSON:
{
"fruits": ["Apple", "Banana", "Orange"],
"employees": [
{ "name": "John", "job": "Developer" },
{ "name": "Jane", "job": "Designer" }
],
"colors": ["red", "blue", "green"]
}
3. 标量(Scalars)—— 单个值
这是最复杂但也最灵活的部分,YAML 提供了多种方式来表示字符串、数字等。
- 字符串:默认不需要引号,但如果字符串包含特殊字符(如
:,{,[,,,&,*,#,?,|,-,<,>,=,!,%,@,`),则需要用单引号''或双引号""包裹。- 单引号:其中的特殊字符会作为普通字符串处理。
''是转义单引号本身。 - 双引号:可以使用转义字符,如
\n换行,\t制表符等。
- 单引号:其中的特殊字符会作为普通字符串处理。
# 无引号字符串(最常用)
unquoted_string: This is a string
# 单引号字符串
single_quoted: 'This is a string with a '':'' character'
# 双引号字符串(支持转义)
double_quoted: "This is a string\nwith a new line"
# 多行字符串(非常实用!)
description: |
This is a multi-line string.
It will preserve line breaks and indentation.
The "|" symbol indicates that the lines will be kept as is.
# 折叠多行字符串(将多行合并为一行,换行符替换为空格)
folded_string: >
This is a folded string.
All these lines will be
collapsed into a single line.
-
数字
integer: 42 float: 3.14159 scientific_notation: 1e-5 # 0.00001 infinity: .inf # 表示无穷大 not_a_number: .nan # 表示非数字 -
布尔值
true_value: true # 也可以是 True, TRUE false_value: false # 也可以是 False, FALSE -
Null
null_value: null # 也可以是 Null, NULL, ~ -
时间与日期(ISO 8601 格式)
datetime: 2001-12-15T02:59:43.1Z # UTC时间 date: 2001-12-15 time: 02:59:43.10
高级特性
1. 锚点(Anchors)与别名(Aliases)—— 避免重复
使用 & 创建一个锚点(引用),使用 * 来复制这个锚点的内容。这非常适用于需要重复大量相同配置的场景。
# 定义锚点,命名为 'base_settings'
base_settings: &base
api_version: v1
environment: production
replicas: 3
# 服务A配置,使用 <<: *base 来合并 base_settings 的所有内容
service_a:
<<: *base # 合并锚点内容
name: service-a
# 可以覆盖锚点中的值
replicas: 1 # 覆盖 base_settings 中的 replicas: 3
# 服务B配置
service_b:
<<: *base
name: service-b
# environment 和 replicas 来自 base_settings
等价于:
service_a:
api_version: v1
environment: production
replicas: 1 # 被覆盖了
name: service-a
service_b:
api_version: v1
environment: production
replicas: 3
name: service-b
2. 多文档支持
一个 YAML 文件可以用 --- 分隔符来包含多个独立的文档。这在 Kubernetes 中非常常见,可以在一个文件中定义多个资源(如一个 Deployment 和一个 Service)。
# 文档 1
---
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
data:
key: value
# 文档 2
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
...
完整示例
# Application Configuration
app_name: My Awesome App
version: 1.0.0
debug: false
# Server Settings
server:
host: 0.0.0.0
port: 8080
ssl: true
allowed_origins:
- https://example.com
- https://localhost:3000
# Database Connection
database:
main_db: &db-prod # 定义锚点
adapter: postgresql
host: db.prod.example.com
port: 5432
database: app_db
username: admin
password: secret_password # 在实际中,应从环境变量读取
pool: 5
# 测试数据库使用生产数据库的大部分配置,但覆盖了 host
test_db:
<<: *db-prod # 合并锚点
host: localhost
database: app_db_test
# Features Flags
feature_flags:
new_ui: true
beta_functionality: false
# Long description
about: |
This is a multi-line description of the application.
It can span multiple lines and preserve its formatting.
Very useful for READMEs or detailed comments.
总结与最佳实践
- 始终使用空格缩进,不要使用 Tab。
- 保持一致的缩进宽度(2 或 4 个空格)。
- 对于简单的键值对,避免不必要的引号。
- 对于复杂的多行字符串,善用
|和>。 - 对于大量重复的配置结构,使用锚点和别名来简化文件,保持 DRY(Don’t Repeat Yourself)原则。
- 敏感信息(如密码、密钥)不要直接写在 YAML 文件中,应该使用环境变量或密钥管理服务。
YAML 因其卓越的可读性和灵活性,已成为现代软件开发中配置文件的事实标准,尤其是在 DevOps、云原生(Kubernetes、Docker Compose)和 CI/CD(GitHub Actions、GitLab CI)等领域。
更多推荐



所有评论(0)