《YAML 语法入门》
1. 简介
YAML 是专门用来写配置文件的标记语言,简洁强大,远比 JSON 易读,是一种通用的数据序列化格式。Kubernetes、CI/CD、Ansible 等大量使用 YAML 描述配置。
- 规范官网:https://yaml.org/
- 参考教程(阮一峰):https://www.ruanyifeng.com/blog/2016/07/yaml.html
- 易百教程:https://www.yiibai.com/yaml/
2. 语法规则
- 大小写敏感。
- 使用缩进表示层级关系。
- 缩进不允许使用 Tab 键,只允许使用空格。
- 缩进的空格数不重要,相同层级的元素左侧对齐即可。
#表示注释,从该字符到行尾都会被解析器忽略(只支持行注释)。
3. 数据结构
YAML 支持三种数据结构:
- 对象(mapping / hashes / dictionary):键值对的集合。
- 数组(sequence / list):一组按次序排列的值。
- 纯量(scalars):单个的、不可再分的值(字符串、数字、布尔、null、时间等)。
4. 基本示例
# 纯量
name: redis
port: 7009
enabled: true
# 数组
command:
- /usr/local/bin/redis-server
- /etc/redis/redis.conf
# 嵌套对象(Kubernetes 风格配置)
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: redis-globalkv
namespace: default
spec:
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
hostNetwork: true
containers:
- name: redis
image: redis:7
ports:
- containerPort: 7009
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
hostPath:
path: /var/run/redis
type: DirectoryOrCreate
对应 JSON:
{
"apiVersion": "apps/v1",
"kind": "DaemonSet",
"metadata": {
"name": "redis-globalkv",
"namespace": "default"
},
"spec": {
"selector": { "matchLabels": { "app": "redis" } },
"template": {
"metadata": { "labels": { "app": "redis" } },
"spec": {
"hostNetwork": true,
"containers": [
{
"name": "redis",
"image": "redis:7",
"ports": [ { "containerPort": 7009 } ],
"volumeMounts": [ { "name": "data", "mountPath": "/data" } ]
}
],
"volumes": [
{ "name": "data", "hostPath": { "path": "/var/run/redis", "type": "DirectoryOrCreate" } }
]
}
}
}
}
5. 工具
- JSON / YAML 互转在线工具:https://www.dute.org/yaml
阅读 —
·
全站 —