YAML指南
简介
YAML Ain't Markup Language
YAML 是一种用于写配置文件的语言,相较于前端熟悉的JSON配置文件,其更为简洁方便,且YAML是JSON的超集。docker-compose,github action,travis ci等都是采用YAML作为流程配置语言。
基本语法规则
- '#'表示注释
- 大小写敏感
- 使用缩进表示层级关系
- 相同层级元素要左对齐
- 字符串可以不用引号
- 缩进时只允许使用空格,禁止使用tab(因为不同的系统tab表示空格数不同)
YAML结构(Structures)
- YAML文件可以由多个文档内容组成,用 --- 表示开头,... 表示结尾,若只有单个文档内容,则可以忽略
---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...
数据类型(data type)
- Scalar (类似js基本数据结构,如boolean,number,string等)
# Integers 整数
canonical: 12345
decimal: +12345
octal: 0o14
hexadecimal: 0xC
# Floating Point 浮点数
canonical: 1.23015e+3
exponential: 12.3015e+02
fixed: 1230.15
negative infinity: -.inf
not a number: .NaN
# Timestamps 日期和时间
canonical: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
spaced: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
# boolean 布尔值
canonical: [ true, false ] # 用true和false表示
# Null
parent: ~ # Null 用 ~ 表示
# String 字符串
canonical: just a str. # 没有引号,若存在特殊字符,必须用引号标注
single quoted: 'just a str.' # 单引号,会转义特殊字符
double quote: "just a str" # 双引号,原样输出
# 多行字符串,换行符会被转为空格
plain:
This unquoted scalar
spans many lines.
quoted: "So does this
quoted scalar.\n"
# 多行字符串可以使用|保留换行符,使用>折叠换行
accomplishment: >
Mark set a major league
home run record in 1998.
stats: |
65 Home Runs
0.278 Batting Average
# + 保留文字块末尾的换行,- 删除字符串末尾的换行
strip: |-
text↓
clip: |
text↓
keep: |+
text↓
- Sequence 数组
Block sequences indicate each entry with a dash and space ( “- ”)
数组由短横线和一个空格组成(- )
# 基本写法
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# 行内表示法
- [name , hr, avg ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa , 63, 0.288]
- Mapping 对象
Mappings use a colon and space (“: ”) to mark each key: value pair.
对象是由冒号分割的健值对表示
# 基本写法
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In
# 花括号写法
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
hr: 63,
avg: 0.288
}
- 复合结构
由上述基本数据类型组合
# Mapping Scalars to Sequences 对象的值是数组
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves
# Sequence of Mappings 对象数组
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288
# 任意组合
---
Time: 2001-11-23 15:01:42 -5
User: ed
Warning:
This is an error message
for the log file
---
Time: 2001-11-23 15:02:31 -5
User: ed
Warning:
A slightly different error
message.
---
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
Unknown variable "bar"
Stack:
- file: TopClass.py
line: 23
code: |
x = MoreObject("345\n")
- file: MoreClass.py
line: 58
code: |-
foo = bar
引用
Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - “&”), and are then aliased (referenced with an asterisk - “*”) thereafter.
& 用来建立锚点, * 用来引用锚点
# Sammy Sosa 出现两次
hr:
- Mark McGwire
# Following node labeled SS
- &SS Sammy Sosa
rbi:
- *SS # Subsequent occurrence
- Ken Griffey
# 一般场景会用来定义全局环境变量,<< 标记表示合并到当前数据中
defaults: &defaults
adapter: postgres
host: localhost
development:
database: myapp_development
<<: *defaults
test:
database: myapp_test
<<: *defaults