시작하기
기본 구조
YAML은 중첩에 들여쓰기(탭이 아닌 공백)를 사용합니다. 매핑은 key: value, 시퀀스는 - item을 씁니다. 인라인 문법은 리스트에 [], 맵에 {}를 사용합니다. 주석은 #을 씁니다.
# YAML uses indentation for structure
# Comments start with #
# Key-value pairs (mappings)
name: Alice
age: 30
# Nested mappings (use consistent indentation)
person:
name: Bob
age: 25
address:
city: NYC
zip: 10001
# Sequences (lists)
hobbies:
- reading
- coding
- music
# Inline syntax
numbers: [1, 2, 3]
coords: {x: 10, y: 20}주석
주석은 #으로 시작하며 앞에 공백이 있거나 줄 시작이어야 합니다. 블록 스칼라(|와 >) 안에서 #은 주석이 아니라 리터럴 내용입니다. 여러 줄 주석 문법은 없으므로 각 줄에 #이 필요합니다.
# Full-line comment
key: value # Inline comment (whitespace before # required)
# Comments can appear anywhere
# - before documents
# - inside sequences
list:
- a # first item
- b # second item
# Block scalar headers DO accept comments
text: | # literal block
line one
# But the content of block scalars is literal,
# so # inside is NOT a comment:
literal: |
# this is part of the string, not a comment들여쓰기 규칙
YAML은 들여쓰기에 탭을 엄격히 금지하며 공백만 허용합니다. 들여쓰기는 한 수준 안에서 일관되면 되고 고정된 칸 수일 필요는 없습니다. 시퀀스의 -는 들여쓰기의 일부입니다. 탭과 공백을 섞으면 파서 오류가 납니다.
# Use SPACES only — tabs are forbidden for indentation
# 2 spaces is the most common convention
mapping:
nested:
deeply_nested: value
# Sequences can be indented at the same level as the key
items:
- one
- two
# Or indented further (both are valid)
items2:
- one
- two
# WRONG: tab characters cause parser errors
# bad: value (tab before value)
# Hyphen counts as indentation start
- item1
- item2문서 시작과 끝
---는 YAML 문서의 시작을, ...은 끝을 표시합니다. 한 파일에 ---로 구분된 여러 문서(문서 스트림)를 담을 수 있습니다. 단일 문서 설정 파일에서는 맨 앞의 ---가 선택이지만 파서에 힌트를 주므로 권장됩니다.
# --- separates documents in a stream
# ... ends a document (optional)
---
name: first document
value: 1
...
---
name: second document
value: 2
...
# A single document needs no markers
key: value
# But --- is recommended at the start of files
# to disambiguate from plain text
---
apiVersion: v1
kind: ConfigMap흔한 함정
콜론이 매핑 구분자가 되려면 뒤에 공백이 필요합니다. YAML 1.1과 1.2는 yes/no/on/off(1.1은 불리언, 1.2는 문자열)와 8진 리터럴에서 다릅니다. 빈 값은 빈 문자열과 구분되는 null입니다. 많은 파서(PyYAML)가 아직 1.1 규칙을 따릅니다.
# Colon needs a space after it
key:value # WRONG: parsed as a single string "key:value"
key: value # correct
# Yes/No/On/Off are NOT booleans in YAML 1.2
# (they WERE in YAML 1.1 — common gotcha)
answer: yes # YAML 1.1: true; YAML 1.2: "yes" string
# Numbers with leading zeros
version: 010 # YAML 1.1: octal 8; YAML 1.2: string "010"
# Unquoted strings with special chars
url: example.com/path # OK
url: example.com:8080 # WRONG: parsed as mapping with key example.com
# Empty values
empty: # null
empty2: ~ # explicit null
empty3: "" # empty string (different from null)YAML vs JSON
YAML 1.2는 JSON이 엄격한 부분 집합이 되도록 설계되어 모든 JSON 파일이 유효한 YAML입니다. YAML은 주석, 블록 구조, 앵커, 여러 줄 문자열, 태그를 추가합니다. JSON은 모든 키와 문자열 값을 인용해야 하지만 YAML은 일반 스칼라에 대해 이를 완화합니다.
# JSON is a strict subset of YAML 1.2
# Every valid JSON document is valid YAML
# JSON:
{"name": "Alice", "age": 30, "hobbies": ["a", "b"]}
# Equivalent YAML:
name: Alice
age: 30
hobbies:
- a
- b
# YAML adds: comments, multi-line strings, anchors,
# relaxed quoting, tags, multiple documents
# YAML removes: mandatory quotes around strings,
# commas, braces (in block style)
# YAML is a superset of JSON — not the other way.
# Comments and anchors are not valid JSON.스칼라(문자열, 숫자, 불리언, Null)
일반 및 따옴표 문자열
일반 문자열은 숫자, 불리언, null, 날짜처럼 보이지 않으면 따옴표가 필요 없습니다. 작은따옴표는 '를 두 번 써서('') 이스케이프할 뿐 다른 이스케이프는 없습니다. 큰따옴표는 전체 이스케이프 시퀀스(\n, \t, \uXXXX)를 지원합니다. 따옴표를 쓰면 문자열 타입이 강제됩니다.
# Plain strings (no quotes) — most common
name: Alice
path: /usr/local/bin
url: https://example.com
# Single-quoted — escape ' by doubling
msg: 'it''s fine'
# Double-quoted — supports escapes
greeting: "Hello\nWorld"
unicode: "\u03B1" # Greek alpha
tab: "col1\tcol2"
# Multi-word plain strings are fine
description: This is a plain string with spaces
# Strings that look like other types must be quoted
version: "1.0" # string, not float
notBool: "true" # string, not boolean
notNull: "null" # string, not null
date: "2024-01-01" # string, not date숫자
YAML 1.2는 8진수에 0o를 씁니다(YAML 1.1은 맨 앞 0 사용). 숫자의 밑줄은 가독성을 위해 허용됩니다. .inf와 .nan은 특수 부동소수 리터럴입니다. 문자열이어야 하지만 숫자처럼 보이는 값(버전, 전화번호, ID)은 따옴표로 감싸세요.
# Integers
int: 42
negative: -17
positive: +100
underscored: 1_000_000 # readable grouping (YAML 1.2)
# Octal & hex (YAML 1.2 prefixes)
octal: 0o17 # = 15 decimal
hex: 0xFF # = 255 decimal
binary: 0b1010 # = 10 decimal
# Floats
pi: 3.14159
exp: 1.0e+3 # 1000.0
neg_exp: -2.5e-4
# Special float values (IEEE 754)
infinity: .inf
neg_infinity: -.inf
not_a_number: .nan
# To force a string that looks numeric:
version: "1.0"
phone: "555-1234"불리언
YAML 1.2는 불리언을 true/false(그리고 True/False, TRUE/FALSE)로 좁혔습니다. YAML 1.1(PyYAML 사용)은 yes/no/on/off/y/n을 불리언으로 취급해 유명한 버그 원인이 됩니다(예: 노르웨이 'no' → false). 이런 문자열을 문자 그대로 쓰려면 항상 따옴표로 감싸세요.
# YAML 1.2 — only these are booleans:
enabled: true
disabled: false
# YAML 1.1 ALSO accepts (common gotcha):
# yes, no, on, off, y, n, Y, N
# These are strings in 1.2 but booleans in 1.1
# To force a string:
answer: "yes" # always a string
option: "on"
flag: "y"
# PyYAML (1.1 rules) parses these as booleans:
# yes -> True, no -> False, on -> True, off -> False
# This breaks "no" as an answer or country code!
# Safe practice: quote if you mean the literal string
country: "no" # Norway country code, not FalseNull 값
YAML은 null, Null, NULL, ~, 빈 값을 null로 받습니다. 빈 값(콜론 뒤에 아무것도 없는 키)은 빈 문자열 ""과 구분되는 null입니다. 파서는 YAML null을 호스트 언어의 null 값(None, null, nil)으로 매핑합니다.
# All of these represent null/None/null
key1: null
key2: Null
key3: NULL
key4: ~
key5: # empty value
# Distinguish null from empty string
empty_string: ""
null_value: null
# In sequences
list:
- value
- null # explicit null item
- another
# In nested structures
config:
timeout: null # explicitly unset
retries: 3
# Parsers convert to language-specific null:
# Python -> None, JavaScript -> null, Go -> nil날짜와 타임스탬프
ISO 8601 날짜와 타임스탬프는 대부분의 파서가 네이티브 타입으로 인식합니다. 따옴표 없는 YYYY-MM-DD는 날짜가 되고 시간이 붙으면 날짜시간이 됩니다. 문자열로 유지하려면 따옴표로 감싸세요. 시간대 표시자(Z, +08:00)를 지원합니다.
# Date (ISO 8601)
date: 2024-01-15
# Datetime (ISO 8601)
datetime: 2024-01-15T14:30:00
datetime_tz: 2024-01-15T14:30:00Z
datetime_offset: 2024-01-15T14:30:00+08:00
datetime_space: 2024-01-15 14:30:00
# To force string (not a date):
not_a_date: "2024-01-15"
not_a_date2: '2024-01-15'
# Parsers typically return datetime objects
# Python: datetime.date / datetime.datetime
# JavaScript: Date (depending on library)타입 추론
YAML 타입 시스템은 스키마로 따옴표 없는 스칼라를 해석합니다. Failsafe 스키마는 모든 것을 문자열로 취급하고 JSON과 Core 스키마는 int, float, bool, null, date를 추론합니다. 필요하면 따옴표나 명시적 태그(!!str, !!int)로 해석을 덮어쓰세요.
# YAML infers types from unquoted scalars
str: hello # string
int: 42 # integer
float: 3.14 # float
bool: true # boolean
null_val: null # null
date: 2024-01-01 # date
list: [1, 2, 3] # sequence
# Force string type with quotes
str_version: "42"
str_date: "2024-01-01"
str_bool: "true"
# Or with the !!str tag
forced: !!str 42 # string "42"
forced_int: !!int "42" # integer 42
# Resolution depends on the schema
# Failsafe: everything is a string
# JSON/Core: numbers, bools, null inferred매핑
단순 매핑
매핑은 key: value 쌍이며 키는 보통 문자열입니다. 키는 모든 스칼라(숫자, 불리언, null까지)가 될 수 있습니다. 중복 키는 권장되지 않고 파서별로 동작이 다릅니다(보통 마지막 우선). 린터로 실수로 인한 중복을 잡으세요.
# A mapping is a set of key: value pairs
name: Alice
age: 30
email: [email protected]
# Keys can be any scalar type (string, number, bool)
"string key": value
123: numeric key
true: boolean key
# Duplicate keys are technically discouraged
# but some parsers allow them (last wins)
key: first
key: second # overrides "first" in many parsers
# Values can be any type
mixed:
string: text
number: 42
list: [1, 2, 3]
nested:
deep: value중첩 매핑
중첩 매핑은 자식 키를 들여써서 만듭니다. 들여쓰기는 한 수준 안에서 일관되어야 합니다. 고정 크기는 없지만 2칸이 사실상 표준입니다. 깊은 중첩은 가독성을 떨어뜨리므로 매우 깊은 구조는 평탄화를 고려하세요.
# Nest mappings with consistent indentation
server:
host: localhost
port: 8080
ssl:
enabled: true
cert: /etc/ssl/cert.pem
key: /etc/ssl/key.pem
database:
primary:
host: db1.example.com
port: 5432
replica:
host: db2.example.com
port: 5432
# Indentation level is up to you — just be consistent
# 2 spaces is the most common convention시퀀스 매핑
매핑과 시퀀스는 자유롭게 합성됩니다. 흔한 패턴은 매핑의 시퀀스(레코드 목록)로, 각 -가 항목을 시작하고 정렬된 키가 그 항목에 속합니다. 이후 키의 들여쓰기는 - 뒤의 첫 키와 정렬되어야 합니다.
# Values in a mapping can be sequences
servers:
- web1.example.com
- web2.example.com
- web3.example.com
# Sequence of mappings (very common)
users:
- name: Alice
age: 30
- name: Bob
age: 25
# Each - starts a new item; aligned keys form one mapping
services:
- name: api
port: 8080
env:
- dev
- prod
- name: web
port: 3000
# Mixed: mapping containing sequence containing mapping
config:
endpoints:
- path: /health
method: GET
- path: /users
method: POST복잡한 키
YAML은 ? 키 표시자로 모든 스칼라나 컬렉션을 키로 허용합니다. 설정 파일에서는 드물지만 조회 테이블(예: 지역+인스턴스별 가격)에 유용합니다. 복잡한 키는 읽기 불편해 대부분 설정 파일은 일반 문자열 키를 고수합니다.
# Keys can be complex objects using ? notation
? key1
: value1
# A mapping as a key
? host: localhost
port: 8080
: connection1
# A sequence as a key
? [a, b, c]
: indexed_value
# Practical (rare) use: matrix lookup
? [us-east-1, t2.micro]
: 0.0116
? [us-east-1, t2.small]
: 0.023
# In flow style:
{[a, b]: value, {x: 1}: other}
# Most config files just use plain string keys
simple: value인라인(플로우) 매핑
플로우 스타일은 매핑에 {}, 시퀀스에 []를 써서 JSON과 비슷합니다. 한 줄의 짧고 압축적인 데이터에 유용합니다. JSON과 달리 YAML은 후행 쉼표를 허용하지 않습니다. 플로우와 블록 스타일을 자유롭게 섞되 설정 파일의 가독성을 위해 블록을 선호하세요.
# Flow style mapping (like JSON)
point: {x: 10, y: 20}
config: {host: localhost, port: 8080}
# Nested flow mappings
nested: {a: {b: {c: value}}}
# Mixed flow and block
block_key:
flow_value: {x: 1, y: 2}
another: value
# Flow with sequences
mixed: {nums: [1, 2, 3], name: test}
# Quoting still works in flow style
quoted: {"key with space": "value", count: 3}
# Trailing comma is NOT allowed in YAML flow
bad: {a: 1, b: 2,} # parse error키 순서와 스타일
YAML 명세는 매핑 순서를 보존하지만 호스트 언어 객체는 그렇지 않을 수 있습니다(최신 dict는 보존). 설정 가독성을 위해 관련 키를 묶고 일관된 이름(snake_case 또는 camelCase)을 쓰며 섹션을 구분하는 주석을 추가하세요.
# YAML mappings are ORDERED (unlike JSON spec, though
# most JSON parsers preserve insertion order too)
# But language objects may not preserve order:
# Python dict (3.7+): preserves order
# Ruby Hash: preserves order
# JSON object: technically unordered
# Consistent key style improves readability
config:
server:
host: localhost # snake_case
port: 8080
max_connections: 100
database:
host: db.example.com
port: 5432
connection_pool: 10
# Group related keys together
# Use comments to delineate sections
app:
# networking
host: 0.0.0.0
port: 3000
# limits
timeout: 30
retries: 3시퀀스
블록 시퀀스
블록 시퀀스는 각 항목 앞에 -(하이픈 + 공백)를 씁니다. 항목은 스칼라, 매핑, 중첩 시퀀스 등 모든 타입이 될 수 있습니다. -는 들여쓰기의 일부로 계산되므로 매핑 항목의 이후 키는 하이픈 뒤 첫 키와 정렬됩니다.
# A sequence (list) uses - followed by space
fruits:
- apple
- banana
- cherry
# Sequence as top-level document
- item1
- item2
- item3
# Empty sequence
empty: []
or_with_marker: []
# Sequence with mixed types
mixed:
- string
- 42
- true
- null
- key: value # a mapping as an item중첩 시퀀스
중첩 시퀀스는 - 수준을 더 들여써서 만듭니다. 2수준을 넘으면 읽기 어려워지므로 내부 시퀀스에는 플로우 스타일로 전환하세요. 트리 구조(자식이 있는 매핑의 시퀀스)가 순수 중첩 시퀀스보다 읽기 쉽습니다.
# Sequence of sequences
matrix:
- - 1
- 2
- 3
- - 4
- 5
- 6
# More readable with flow style for inner
matrix2:
- [1, 2, 3]
- [4, 5, 6]
# Deeply nested
tree:
- name: root
children:
- name: child1
children:
- name: grandchild1
- name: child2
# 3D: sequence of sequence of sequence
cube:
- - [1, 2]
- [3, 4]
- - [5, 6]
- [7, 8]]매핑의 시퀀스
매핑의 시퀀스는 가장 흔한 YAML 패턴(레코드 목록)입니다. 각 -가 새 항목을 시작하고 같은 들여쓰기의 이후 키가 그 항목에 속합니다. 가독성을 위해 - 뒤에서 키를 정렬하세요. 빈 매핑 항목은 {}로 씁니다.
# Most common pattern: list of records
users:
- name: Alice
email: [email protected]
roles:
- admin
- user
- name: Bob
email: [email protected]
roles:
- user
# Each - starts a new mapping; aligned keys belong
# to that item. Indent the first key after - by 2 spaces.
servers:
- host: web1.example.com
port: 8080
healthy: true
- host: web2.example.com
port: 8080
healthy: false
# Empty mapping item
list:
- {}
- name: real인라인(플로우) 시퀀스
플로우 시퀀스는 []를 쓰며 블록 시퀀스와 동등합니다. 한 줄의 짧은 목록에 유용합니다. 가독성을 위해 여러 줄에 걸칠 수 있습니다. JSON과 달리 YAML은 후행 쉼표를 금지합니다. 플로우 시퀀스를 블록 매핑과 자유롭게 섞으세요.
# Flow sequence (JSON-like)
numbers: [1, 2, 3]
names: [Alice, Bob, Charlie]
# Nested flow sequences
matrix: [[1, 2], [3, 4]]
# Flow sequence of flow mappings
points: [{x: 1, y: 2}, {x: 3, y: 4}]
# Mixed: block mapping with flow sequence value
config:
ports: [80, 443, 8080]
hosts: [web1, web2, web3]
# Spread across multiple lines (still flow style)
long_list: [
item1,
item2,
item3
]
# NO trailing comma allowed
bad: [1, 2, 3,] # error혼합 및 이종 콘텐츠
YAML은 시퀀스와 매핑에 완전히 이종적인 콘텐츠를 허용하며 어떤 항목이든 어떤 타입이 될 수 있습니다. 이 유연성은 강력하지만 애플리케이션이 구조를 검증해야 합니다. 엄격한 검증에는 스키마(JSON Schema, Cue 등)를 사용하세요.
# Sequences can mix types freely
mixed:
- string
- 42
- true
- null
- [1, 2, 3] # nested sequence
- key: value # mapping
another: value2
- - nested
- sequence
# Heterogeneous mapping values
config:
string_val: text
int_val: 42
list_val: [a, b, c]
map_val: {x: 1, y: 2}
null_val: null
bool_val: true
# YAML has no schema enforcing uniformity —
# the application must validate structure시퀀스 들여쓰기 패턴
키 아래 시퀀스는 들여쓰거나(패턴 1) 같은 수준에 둘 수 있습니다(패턴 2, -가 들여쓰기로 계산되기 때문). 둘 다 유효하므로 하나를 선택해 일관되게 쓰세요. 매핑의 시퀀스에서 항목의 모든 키는 - 뒤 첫 키와 정렬되어야 합니다.
# Pattern 1: sequence indented under key
items:
- a
- b
# Pattern 2: sequence at same level as key
# (the - is treated as indentation)
items:
- a
- b
# Both are valid and produce the same result.
# Pick one and be consistent (most style guides prefer #1).
# Mapping item alignment — both keys align with first
users:
- name: Alice
age: 30
- name: Bob
age: 25
# WRONG: misaligned keys cause parse errors
# users:
# - name: Alice
# age: 30 # one space off — error여러 줄 문자열(폴디드와 리터럴)
리터럴 블록 스칼라(|)
리터럴 블록 스칼라 |는 모든 줄바꿈을 작성된 그대로 보존합니다. 들여쓰기(| 뒤의 양)는 각 줄에서 제거됩니다. 기본 chomping(clip)은 후행 줄바꿈 하나를 유지합니다. 스크립트, 코드, 시, ASCII 아트처럼 리터럴 줄바꿈이 중요한 곳에 사용합니다.
# | preserves newlines as-is
script: |
#!/bin/bash
echo "Hello"
echo "World"
# Output string:
# #!/bin/bash\necho "Hello"\necho "World"\n
poem: |
Roses are red,
Violets are blue,
YAML is clean,
And JSON is too.
# Trailing newline is kept by default (clip mode)
# Use |- to strip, |+ to keep all trailing newlines폴디드 블록 스칼라(>)
폴디드 블록 스칼라 >는 단일 줄바꿈을 공백으로 바꿔 줄을 문단으로 합칩니다. 빈 줄은 리터럴 줄바꿈이 됩니다. 블록 내용보다 더 들여쓴 줄은 리터럴로 보존됩니다(산문 속 코드 샘플에 유용).
# > folds newlines into spaces (paragraphs)
description: >
This is a long paragraph that
spans multiple lines in the YAML
but will be joined into one line
when parsed.
# Output: "This is a long paragraph that spans multiple
# lines in the YAML but will be joined into one line when
# parsed.\n"
# Blank lines preserve a newline
paragraphs: >
First paragraph here.
Second paragraph here.
Third paragraph here.
# More indented lines are preserved literally
example: >
This is folded.
This line is more indented — kept literal.Chomping 표시자(+/-)
Chomping은 후행 줄바꿈을 제어합니다. clip(기본, 표시자 없음)은 하나를 유지하고 strip(-)은 모두 제거하며 keep(+)은 모두 보존합니다. 표시자는 |나 > 바로 뒤에 옵니다(예: |-, |+, >-, >+). Strip은 인라인으로 쓰는 문자열에 유용하고 keep은 드물지만 소스와 정확히 일치합니다.
# Default (clip): single trailing newline
text: |
line1
line2
# Result: "line1\nline2\n"
# Strip (-): remove ALL trailing newlines
text_strip: |-
line1
line2
# Result: "line1\nline2"
# Keep (+): keep ALL trailing newlines
text_keep: |+
line1
line2
# Result: "line1\nline2\n\n\n"
# Same applies to folded scalars
folded_keep: >+
folded
text
들여쓰기 표시자
블록 스칼라 내용이 공백으로 시작하면 숫자로 내용 들여쓰기를 명시해야 합니다(예: |2). 숫자는 구조에 속하는 들여쓰기와 내용의 들여쓰기를 구분합니다. Chomping과 결합하세요: |2-, >4+ 등. 드물게 필요하지만 필요할 때는 필수입니다.
# When the first line starts with spaces, you must
# tell YAML the content indentation explicitly
# Without indicator (ambiguous):
# content:
# indented_line # is the leading space content or not?
# With explicit indentation indicator (digit after | or >)
literal: |2
hello
world
# The "2" means: content is indented 2 spaces past the indicator
# So 4 spaces of indentation = 2 content + 2 extra
# Combined with chomping (order: indent then chomp)
text: |2-
no trailing newline
# Folded with explicit indent
folded: >4
paragraph with
explicit indent
# Most of the time you don't need this — only when
# content legitimately starts with spaces일반 여러 줄 문자열
일반 및 따옴표 스칼라는 여러 줄에 걸칠 수 있고 줄바꿈이 공백으로 폴딩됩니다(>와 비슷하지만 암묵적). 줄바꿈이 문맥과 특수 문자에 의존해 취약합니다. 사소하지 않은 여러 줄 텍스트에는 명시적 |(리터럴)나 >(폴디드) 블록 스칼라를 선호하세요.
# Plain (unquoted) scalars can span lines
# Newlines are folded to spaces (like > but no indicator)
message: this is
a long message
on multiple lines
# Result: "this is a long message on multiple lines"
# Quotes are required if the string contains special chars
quoted: "this is also
a long message
on multiple lines"
# Result: "this is also a long message on multiple lines"
# Plain multi-line breaks at certain chars
# (colons, etc.) — usually fold cleanly
# but be careful with leading colons
# Plain is fragile for multi-line — prefer | or >
safe_literal: |
Use literal block for
predictable multi-line text폴드 vs 리터럴 선택
경험칙: 줄바꿈이 중요하면(스크립트, 설정 파일, 코드) |를, 읽기 쉬운 여러 줄 소스지만 합쳐진 문단을 원하면(설명, 문서) >를 사용하세요. 문자열을 인라인으로 쓸 때 후행 줄바꿈을 제거하려면 |-를 사용하세요.
# Use | (literal) when newlines matter:
script: |
#!/bin/bash
set -e
echo "Step 1"
echo "Step 2"
config_file: |
[default]
region=us-east-1
output=json
# Use > (folded) when you want readable source
# but a single paragraph string:
description: >
This service handles user authentication
and session management. It talks to the
PostgreSQL database and Redis cache.
# Use |- or >- to strip trailing newline
# (useful for inline string usage):
inline_script: |-
echo hello
# Use plain single-line for short strings
short: hello world앵커와 별칭
앵커 정의(&)
&name은 노드(매핑, 시퀀스, 스칼라)에 앵커를 정의합니다. 앵커는 그 위치의 값을 바꾸지 않고 재사용을 위해 노드에 레이블을 붙일 뿐입니다. 별칭(*name)은 앵커된 노드를 이름으로 참조합니다. 앵커는 문서 안에서 사용 전에 정의되어야 합니다.
# &name defines an anchor on a node
defaults: &defaults
adapter: postgres
host: localhost
port: 5432
# The anchor marks the node so it can be reused
# The value is still assigned normally
production:
database: *defaults
# *defaults is an alias — references the anchored node
# Anchors on scalars
version: &ver "1.0.0"
current: *ver
# Anchors on sequences
colors: &colors
- red
- green
- blue
primary: *colors별칭 사용(*)
*name은 앞서 앵커된 노드를 참조하는 별칭입니다. 별칭은 원본과 정체성을 공유합니다(대부분 파서에서 같은 객체). 앵커/별칭은 문서 범위라 --- 문서 경계를 넘어 참조할 수 없습니다. <<(병합 키)와 결합해 덮어쓰기를 계층화하세요.
# Define once, reuse by alias
base: &base
image: nginx:1.25
restart: always
web:
<<: *base
ports:
- "80:80"
api:
<<: *base
ports:
- "8080:8080"
environment:
- DEBUG=true
# Aliases reference the SAME object (by identity)
# In most parsers, mutating one mutates the other
# (though YAML itself is read-only)
# Aliases can't span documents
# Each document has its own anchor namespace앵커 범위
앵커는 문서에 범위가 제한되고 별칭이 참조하기 전에 정의되어야 합니다(전방 참조 불가). 여러 별칭이 같은 앵커를 참조할 수 있습니다. 별칭의 별칭도 동작하며 전이적으로 해석됩니다. 문서 간 참조는 오류입니다.
# Anchors are scoped to a single document
---
# Document 1
shared: &shared
key: value
use: *shared # works
...
---
# Document 2 — &shared is NOT visible here
other: *shared # ERROR: unknown anchor
# Anchors must be defined before the alias
# (forward references are not allowed)
bad: *later # ERROR
later: &later value
# Multiple aliases to the same anchor are fine
template: &tpl
timeout: 30
use1: *tpl
use2: *tpl
use3: *tpl
# Aliasing an alias is allowed
a: &a value
b: &b *a
c: *b # resolves to "value"앵커 값 덮어쓰기
별칭(*name)은 전체 노드를 대체하므로 부분적으로 덮어쓸 수 없습니다. 앵커된 매핑의 개별 키를 덮어쓰려면 병합 키 <<로 앵 커된 매핑을 병합한 뒤 키를 추가하거나 덮어쓰세요. 설정 합성의 표준 패턴입니다.
# Aliases themselves can't be partially overridden —
# an alias replaces the whole node. Use << (merge)
# to combine an anchored mapping with overrides.
defaults: &defaults
timeout: 30
retries: 3
log_level: info
production:
<<: *defaults
log_level: warn # override
host: prod.example.com # add
# Result:
# production:
# timeout: 30
# retries: 3
# log_level: warn
# host: prod.example.com
# Without <<, an alias replaces the whole node:
wrong:
thing: *defaults
# thing is the FULL defaults mapping — can't override시퀀스의 앵커
앵커는 전체 시퀀스, 개별 시퀀스 항목, 시퀀스 안의 매핑에 레이블을 붙일 수 있습니다. << 병합 패턴은 유사한 레코드의 시퀀스(예: 서비스 정의)에서 공통 필드를 공유할 때 특히 유용합니다. 개별 항목은 - &name value로 앵커하세요.
# Anchors work on sequence items too
common: &common
enabled: true
log: stdout
services:
- name: web
<<: *common
port: 80
- name: api
<<: *common
port: 8080
- name: worker
<<: *common
queue: jobs
# Anchoring a whole sequence
endpoints: &endpoints
- /health
- /metrics
- /ready
monitoring:
checks: *endpoints
# Anchoring individual sequence items
list:
- &first one
- two
- *first # "one" again앵커 주의점
앵커 주의점: 별칭은 정체성을 공유하므로(가변 파서에서 하나를 바꾸면 모든 참조에 영향) 인지 부하가 늘고 대부분의 직렬화기(JSON 출력 포함)가 평범한 복사본으로 확장합니다. 마이크로 최적화가 아니라 진짜 재사용(템플릿, 기본값)에 앵커를 사용하세요.
# Caveat 1: shared identity can surprise you
defaults: &defaults
list: [1, 2, 3]
a: *defaults
b: *defaults
# In mutable parsers, a.list and b.list are the SAME list.
# Editing a.list also changes b.list.
# Caveat 2: anchors add cognitive overhead
# Overuse makes YAML hard to read and trace.
# Caveat 3: not all tools preserve anchors on output
# Many serializers expand aliases to plain copies.
# Caveat 4: JSON output loses anchors entirely
# (JSON has no anchor concept).
# Caveat 5: anchors don't work across documents
---
doc1: &x value
use1: *x
---
doc2: *x # ERROR
# Prefer anchors for genuine reuse, not micro-optimization.병합 키(<<)
기본 병합(<<)
병합 키 <<는 매핑(보통 별칭)을 받아 키-값 쌍을 현재 매핑에 병합합니다. 현재 매핑에 명시된 키가 병합된 키를 덮어씁니다. YAML 설정 상속의 표준 패턴입니다.
# << merges a referenced mapping into the current one
defaults: &defaults
adapter: postgres
pool: 5
timeout: 5000
development:
<<: *defaults
database: myapp_dev
host: localhost
production:
<<: *defaults
database: myapp_prod
host: db.example.com
pool: 20 # override
# Result for development:
# adapter: postgres
# pool: 5
# timeout: 5000
# database: myapp_dev
# host: localhost여러 병합
<<는 별칭의 플로우 시퀀스([*a, *b, *c])를 넘겨 여러 매핑을 병합할 수 있습니다. 병합은 왼쪽에서 오른쪽으로 적용되고 중복 키는 나중 병합이 이전 것을 덮어씁니다. 매핑의 명시적 키는 항상 병합된 키를 이깁니다. 여러 << 항목도 허용됩니다.
# << can merge multiple mappings (sequence value)
base: &base
logging: info
retries: 3
security: &security
auth: required
tls: true
service: &service
port: 8080
host: 0.0.0.0
# Merge multiple in one go
production:
<<: [*base, *security, *service]
environment: prod
port: 80 # override service.port
# Later merges override earlier ones for the same key.
# Explicit keys always win over merges.
# You can also have multiple << entries:
combined:
<<: *base
<<: *security
custom: value덮어쓰기와 우선순위
병합 우선순위: 매핑의 명시적 키가 항상 이깁니다. 병합된 매핑 중에서는 시퀀스에서 나중 것이 같은 키에 대해 이전 것을 덮어씁니다. 이를 이용해 기본값 → 역할별 → 인스턴스별 덮어쓰기를 깔끔하게 계층화하세요.
# Explicit keys override merged keys
template: &template
port: 8080
log: info
timeout: 30
instance:
<<: *template
port: 9090 # overrides template.port
log: debug # overrides template.log
host: example.com # added
# Final: {port: 9090, log: debug, timeout: 30, host: example.com}
# Precedence: explicit > later merge > earlier merge
a: &a
k: from_a
x: 1
b: &b
k: from_b
y: 2
result:
<<: [*a, *b]
k: explicit # wins over both a and b
# Final: {k: explicit, x: 1, y: 2}앵커를 쓰는 병합 패턴
병합+앵커 패턴은 Docker Compose와 유사한 설정 파일의 기본입니다. defaults 앵커를 정의 한 뒤 각 서비스가 이를 병합하고 개별 필드를 덮어씁니다. 서비스별 사용자 정의를 잃지 않고 설정을 DRY하게 유지합니다.
# Common pattern: anchor templates, merge + override
defaults: &defaults
image: nginx:1.25
restart: always
logging:
driver: json-file
services:
web:
<<: *defaults
ports: ["80:80"]
api:
<<: *defaults
image: node:20 # override
ports: ["8080:8080"]
environment:
NODE_ENV: production
worker:
<<: *defaults
image: worker:latest
command: ["./run.sh"]
# This is the bread-and-butter of Docker Compose files
# — share base config, override per service.병합의 한계
병합 키 <<는 매핑에만 동작하며 시퀀스와 스칼라는 병합할 수 없습니다. 병합은 얕아서 현재 노드의 중첩 매핑이 병합된 것을 통째로 대체합니다(깊은 병합 없음). 깊은 병합이 필요하면 데이터를 재구성하거나 애플리케이션 코드에서 처리하세요.
# << only works for MAPPINGS, not sequences or scalars
list_template: &list [1, 2, 3]
# This does NOT merge list items:
combined:
<<: *list # WRONG: *list is a sequence, not a mapping
extra: value # parse error or unexpected behavior
# Deep merge is NOT supported
parent: &parent
nested:
a: 1
b: 2
child:
<<: *parent
nested:
c: 3 # REPLACES parent.nested entirely
# Result: {nested: {c: 3}} — NOT {nested: {a:1, b:2, c:3}}
# To deep-merge, you must do it in application code
# or restructure the data.병합 키 상태와 폐기
<< 병합 키는 YAML 1.1 확장이며 YAML 1.2 코어 명세에서 제거되었습니다. 실제로는 대부분의 파서(PyYAML, js-yaml, ruamel, SnakeYAML)가 여전히 지원하지만 엄격한 1.2 파서는 거부합니다. 지금은 써도 되지만 비표준임을 알아 두세요. 새 형식에는 진짜 상속이 있는 설정 언어(Cue, Jsonnet, Dhall)를 고려하세요.
# IMPORTANT: the << merge key was REMOVED in YAML 1.2
# It was a YAML 1.1 feature.
# In practice, many parsers still support it:
# - PyYAML: supports (1.1 mode)
# - js-yaml: supports (opt-in)
# - ruamel.yaml: supports
# - SnakeYAML: supports
# - LibYAML: supports
# But strict YAML 1.2 parsers reject it:
# new_yaml_1_2_strict:
# <<: *template # ERROR in strict 1.2
# Recommendation:
# - Use << for now (widely supported)
# - Document that your files rely on it
# - For new formats, consider composition in code
# or a config language with proper inheritance
# (e.g. Dhall, Cue, Jsonnet)
# Alternative without <<:
# just duplicate or use application-level templating문서 표시자와 지시문
단일 문서
단일 YAML 문서는 표시자 없이도 잘 동작합니다. 맨 앞의 ---는 '이것은 YAML'임을 알리고 일반 텍스트와 구분하는 관례입니다. ... 끝 표시자는 선택이며 단일 문서 파일에서는 드물게 씁니다.
# A single YAML document needs no markers
key: value
list:
- a
- b
# But a leading --- is a common convention
# to mark "this is YAML, not plain text"
---
key: value
# The trailing ... (end marker) is optional
# for a single document
key: value
...여러 문서(스트림)
YAML 스트림은 ---로 구분된 문서의 시퀀스입니다. 각 문서는 독립적으로 파싱됩니다. Kubernetes(파일당 여러 객체), 정적 사이트 생성기, 로그 파일에서 흔합니다. 파서에서 load_all()이나 동등한 함수로 문서를 반복하세요.
# A YAML stream is multiple documents separated by ---
---
name: first
value: 1
---
name: second
value: 2
---
name: third
value: 3
# Each document is independent — anchors don't cross
# Use a parser's load_all() / load_multi() to read them
# Python (PyYAML):
# for doc in yaml.safe_load_all(stream):
# print(doc)
# Common use cases:
# - Kubernetes: multiple objects in one file
# - Blog generators: front matter + content
# - Log files: one record per document
# - CI/CD: multi-step pipelines문서 끝 표시자(...)
... 표시자는 문서를 명시적으로 끝냅니다. 대부분 선택이지만 내용이 모호할 수 있을 때(예: ---를 포함한 리터럴 블록) 유용합니다. 스트리밍 파서에도 문서 끝을 알립니다. 손으로 쓴 YAML에서는 드물지만 프로그램 출력에서는 흔합니다.
# ... explicitly ends a document
---
key: value
...
# Anything after ... is a new document or stream end
# Useful when a document's content might be ambiguous
# without an explicit end:
---
message: |
Some content
---
that looks like a separator
...
---
next: document
# Without ... the parser might think the ---
# inside the literal block is a document separator
# (though block scalars usually prevent this)
# ... is also useful in programmatic output to flush지시문
지시문은 문서 내용 앞에 나타나 파서를 설정합니다. %YAML은 버전을, %TAG는 태그 접두사 단축을 선언합니다. 지시문은 문서 범위라 다음 문서에만 적용됩니다. 대부분 설정 파일은 지시문을 생략하고 파서 기본값(보통 1.1 또는 1.2 이중 모드)에 의존합니다.
# Directives appear at the very top, before content
# %YAML — declare YAML version
%YAML 1.2
---
key: value
# %TAG — declare a tag prefix
%TAG !e! tag:example.com,2024:
---
data: !e!custom value
# Multiple directives are allowed
%YAML 1.2
%TAG !e! tag:example.com,2024:
%TAG !yaml! tag:yaml.org,2002:
---
value: !yaml!str hello
# Directives are document-scoped — they apply to the
# next document only and must be repeated for each.
# Most config files omit directives and use defaults.문서 스트림 예제
문서 스트림은 널리 쓰입니다. Kubernetes는 여러 객체(Namespace, Deployment, Service)를 한 파일에 묶을 때 사용합니다. Helm 템플릿, CI 로그, 정적 사이트 생성기(프런트 매터 + 콘텐츠)도 스트림을 씁니다. 각 문서는 독립적이고 자체 지시문을 가질 수 있습니다.