Skip to content

YAML 치트시트

설정 파일을 위한 사람 친화적 데이터 직렬화 표준.

01

시작하기

기본 구조

YAML은 중첩에 들여쓰기(탭이 아닌 공백)를 사용합니다. 매핑은 key: value, 시퀀스는 - item을 씁니다. 인라인 문법은 리스트에 [], 맵에 {}를 사용합니다. 주석은 #을 씁니다.

yaml
# 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}

주석

주석은 #으로 시작하며 앞에 공백이 있거나 줄 시작이어야 합니다. 블록 스칼라(|와 >) 안에서 #은 주석이 아니라 리터럴 내용입니다. 여러 줄 주석 문법은 없으므로 각 줄에 #이 필요합니다.

yaml
# 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은 들여쓰기에 탭을 엄격히 금지하며 공백만 허용합니다. 들여쓰기는 한 수준 안에서 일관되면 되고 고정된 칸 수일 필요는 없습니다. 시퀀스의 -는 들여쓰기의 일부입니다. 탭과 공백을 섞으면 파서 오류가 납니다.

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 문서의 시작을, ...은 끝을 표시합니다. 한 파일에 ---로 구분된 여러 문서(문서 스트림)를 담을 수 있습니다. 단일 문서 설정 파일에서는 맨 앞의 ---가 선택이지만 파서에 힌트를 주므로 권장됩니다.

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 규칙을 따릅니다.

yaml
# 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은 일반 스칼라에 대해 이를 완화합니다.

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.
02

스칼라(문자열, 숫자, 불리언, Null)

일반 및 따옴표 문자열

일반 문자열은 숫자, 불리언, null, 날짜처럼 보이지 않으면 따옴표가 필요 없습니다. 작은따옴표는 '를 두 번 써서('') 이스케이프할 뿐 다른 이스케이프는 없습니다. 큰따옴표는 전체 이스케이프 시퀀스(\n, \t, \uXXXX)를 지원합니다. 따옴표를 쓰면 문자열 타입이 강제됩니다.

yaml
# 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)은 따옴표로 감싸세요.

yaml
# 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
# 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 False

Null 값

YAML은 null, Null, NULL, ~, 빈 값을 null로 받습니다. 빈 값(콜론 뒤에 아무것도 없는 키)은 빈 문자열 ""과 구분되는 null입니다. 파서는 YAML null을 호스트 언어의 null 값(None, null, nil)으로 매핑합니다.

yaml
# 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)를 지원합니다.

yaml
# 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
# 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
03

매핑

단순 매핑

매핑은 key: value 쌍이며 키는 보통 문자열입니다. 키는 모든 스칼라(숫자, 불리언, null까지)가 될 수 있습니다. 중복 키는 권장되지 않고 파서별로 동작이 다릅니다(보통 마지막 우선). 린터로 실수로 인한 중복을 잡으세요.

yaml
# 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칸이 사실상 표준입니다. 깊은 중첩은 가독성을 떨어뜨리므로 매우 깊은 구조는 평탄화를 고려하세요.

yaml
# 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

시퀀스 매핑

매핑과 시퀀스는 자유롭게 합성됩니다. 흔한 패턴은 매핑의 시퀀스(레코드 목록)로, 각 -가 항목을 시작하고 정렬된 키가 그 항목에 속합니다. 이후 키의 들여쓰기는 - 뒤의 첫 키와 정렬되어야 합니다.

yaml
# 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은 ? 키 표시자로 모든 스칼라나 컬렉션을 키로 허용합니다. 설정 파일에서는 드물지만 조회 테이블(예: 지역+인스턴스별 가격)에 유용합니다. 복잡한 키는 읽기 불편해 대부분 설정 파일은 일반 문자열 키를 고수합니다.

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은 후행 쉼표를 허용하지 않습니다. 플로우와 블록 스타일을 자유롭게 섞되 설정 파일의 가독성을 위해 블록을 선호하세요.

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
# 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
04

시퀀스

블록 시퀀스

블록 시퀀스는 각 항목 앞에 -(하이픈 + 공백)를 씁니다. 항목은 스칼라, 매핑, 중첩 시퀀스 등 모든 타입이 될 수 있습니다. -는 들여쓰기의 일부로 계산되므로 매핑 항목의 이후 키는 하이픈 뒤 첫 키와 정렬됩니다.

yaml
# 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수준을 넘으면 읽기 어려워지므로 내부 시퀀스에는 플로우 스타일로 전환하세요. 트리 구조(자식이 있는 매핑의 시퀀스)가 순수 중첩 시퀀스보다 읽기 쉽습니다.

yaml
# 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 패턴(레코드 목록)입니다. 각 -가 새 항목을 시작하고 같은 들여쓰기의 이후 키가 그 항목에 속합니다. 가독성을 위해 - 뒤에서 키를 정렬하세요. 빈 매핑 항목은 {}로 씁니다.

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은 후행 쉼표를 금지합니다. 플로우 시퀀스를 블록 매핑과 자유롭게 섞으세요.

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 등)를 사용하세요.

yaml
# 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, -가 들여쓰기로 계산되기 때문). 둘 다 유효하므로 하나를 선택해 일관되게 쓰세요. 매핑의 시퀀스에서 항목의 모든 키는 - 뒤 첫 키와 정렬되어야 합니다.

yaml
# 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
05

여러 줄 문자열(폴디드와 리터럴)

리터럴 블록 스칼라(|)

리터럴 블록 스칼라 |는 모든 줄바꿈을 작성된 그대로 보존합니다. 들여쓰기(| 뒤의 양)는 각 줄에서 제거됩니다. 기본 chomping(clip)은 후행 줄바꿈 하나를 유지합니다. 스크립트, 코드, 시, ASCII 아트처럼 리터럴 줄바꿈이 중요한 곳에 사용합니다.

yaml
# | 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

폴디드 블록 스칼라(>)

폴디드 블록 스칼라 >는 단일 줄바꿈을 공백으로 바꿔 줄을 문단으로 합칩니다. 빈 줄은 리터럴 줄바꿈이 됩니다. 블록 내용보다 더 들여쓴 줄은 리터럴로 보존됩니다(산문 속 코드 샘플에 유용).

yaml
# > 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은 드물지만 소스와 정확히 일치합니다.

yaml
# 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+ 등. 드물게 필요하지만 필요할 때는 필수입니다.

yaml
# 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

일반 여러 줄 문자열

일반 및 따옴표 스칼라는 여러 줄에 걸칠 수 있고 줄바꿈이 공백으로 폴딩됩니다(>와 비슷하지만 암묵적). 줄바꿈이 문맥과 특수 문자에 의존해 취약합니다. 사소하지 않은 여러 줄 텍스트에는 명시적 |(리터럴)나 >(폴디드) 블록 스칼라를 선호하세요.

yaml
# 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 리터럴 선택

경험칙: 줄바꿈이 중요하면(스크립트, 설정 파일, 코드) |를, 읽기 쉬운 여러 줄 소스지만 합쳐진 문단을 원하면(설명, 문서) >를 사용하세요. 문자열을 인라인으로 쓸 때 후행 줄바꿈을 제거하려면 |-를 사용하세요.

yaml
# 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
06

앵커와 별칭

앵커 정의(&)

&name은 노드(매핑, 시퀀스, 스칼라)에 앵커를 정의합니다. 앵커는 그 위치의 값을 바꾸지 않고 재사용을 위해 노드에 레이블을 붙일 뿐입니다. 별칭(*name)은 앵커된 노드를 이름으로 참조합니다. 앵커는 문서 안에서 사용 전에 정의되어야 합니다.

yaml
# &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은 앞서 앵커된 노드를 참조하는 별칭입니다. 별칭은 원본과 정체성을 공유합니다(대부분 파서에서 같은 객체). 앵커/별칭은 문서 범위라 --- 문서 경계를 넘어 참조할 수 없습니다. <<(병합 키)와 결합해 덮어쓰기를 계층화하세요.

yaml
# 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

앵커 범위

앵커는 문서에 범위가 제한되고 별칭이 참조하기 전에 정의되어야 합니다(전방 참조 불가). 여러 별칭이 같은 앵커를 참조할 수 있습니다. 별칭의 별칭도 동작하며 전이적으로 해석됩니다. 문서 간 참조는 오류입니다.

yaml
# 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)은 전체 노드를 대체하므로 부분적으로 덮어쓸 수 없습니다. 앵커된 매핑의 개별 키를 덮어쓰려면 병합 키 <<로 앵커된 매핑을 병합한 뒤 키를 추가하거나 덮어쓰세요. 설정 합성의 표준 패턴입니다.

yaml
# 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로 앵커하세요.

yaml
# 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 출력 포함)가 평범한 복사본으로 확장합니다. 마이크로 최적화가 아니라 진짜 재사용(템플릿, 기본값)에 앵커를 사용하세요.

yaml
# 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.
07

병합 키(<<)

기본 병합(<<)

병합 키 <<는 매핑(보통 별칭)을 받아 키-값 쌍을 현재 매핑에 병합합니다. 현재 매핑에 명시된 키가 병합된 키를 덮어씁니다. YAML 설정 상속의 표준 패턴입니다.

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])를 넘겨 여러 매핑을 병합할 수 있습니다. 병합은 왼쪽에서 오른쪽으로 적용되고 중복 키는 나중 병합이 이전 것을 덮어씁니다. 매핑의 명시적 키는 항상 병합된 키를 이깁니다. 여러 << 항목도 허용됩니다.

yaml
# << 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

덮어쓰기와 우선순위

병합 우선순위: 매핑의 명시적 키가 항상 이깁니다. 병합된 매핑 중에서는 시퀀스에서 나중 것이 같은 키에 대해 이전 것을 덮어씁니다. 이를 이용해 기본값 → 역할별 → 인스턴스별 덮어쓰기를 깔끔하게 계층화하세요.

yaml
# 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하게 유지합니다.

yaml
# 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.

병합의 한계

병합 키 <<는 매핑에만 동작하며 시퀀스와 스칼라는 병합할 수 없습니다. 병합은 얕아서 현재 노드의 중첩 매핑이 병합된 것을 통째로 대체합니다(깊은 병합 없음). 깊은 병합이 필요하면 데이터를 재구성하거나 애플리케이션 코드에서 처리하세요.

yaml
# << 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)를 고려하세요.

yaml
# 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
08

타입 태그

내장 태그

내장 태그는 !! 접두사(tag:yaml.org,2002:의 단축)를 씁니다. 스키마 추론과 무관하게 특정 타입을 강제합니다. 흔한 태그: !!str, !!int, !!float, !!bool, !!null, !!binary, !!map, !!seq, !!omap, !!set, !!timestamp. 추론이 틀릴 것 같을 때 유용합니다.

yaml
# YAML tags use !! prefix for built-in types
# (the long form is tag:yaml.org,2002:)

# Common built-in tags
str: !!str hello
int: !!int 42
float: !!float 3.14
bool: !!bool true
null: !!null null
binary: !!binary "SGVsbG8="
map: !!map {a: 1}
seq: !!seq [1, 2]
omap: !!omap
  - a: 1
  - b: 2
set: !!set
  ? item1
  ? item2
timestamp: !!timestamp 2024-01-01T00:00:00Z
merge: !!merge "<<"   # the merge key tag

# Tags force a specific type regardless of inference
forced_str: !!str 42        # "42" string
forced_int: !!int "42"      # 42 integer
forced_bool: !!bool "yes"   # true

타입 강제

태그는 스키마 추론을 덮어쓰고 특정 타입을 강제합니다. 가장 흔한 용도는 숫자/불리언/날짜처럼 보이는 문자열이 강제 변환되지 않게 하는 !!str입니다. !!int와 !!float는 숫자 문자열을 파싱할 수 있습니다. 호스트 애플리케이션이 특정 타입을 필요로 할 때 태그가 필수입니다.

yaml
# Without tags, type depends on schema inference
value: 42          # integer (Core schema)
value: "42"        # string (quoted)
value: !!str 42    # string (forced by tag)

# Common forcing scenarios
version: !!str 1.0       # "1.0" string, not float
phone: !!str 5551234     # string, not int
answer: !!str yes        # string, not bool (1.1)
region: !!str no         # string "no", not False (1.1)

# Force numeric parsing from strings
count: !!int "100"       # 100 integer
ratio: !!float "0.5"     # 0.5 float

# Force bool from strings
enabled: !!bool "yes"    # true
enabled: !!bool "off"    # false

# Force null
empty: !!null ""         # null
empty: !!null "~"        # null

커스텀 태그

커스텀 태그는 단일 ! 접두사를 쓰며 애플리케이션이 정의합니다. 호스트 애플리케이션이 각 태그의 생성자를 등록해야 합니다. 안전 로더(권장)는 기본적으로 알 수 없는 태그를 거부하므로 명시적으로 허용해야 합니다. 라이브러리별 태그(PyYAML의 python/object 등)는 위험할 수 있어 안전 로더에서 비활성화됩니다.

yaml
# Application-specific tags use ! prefix
# The application's YAML loader must handle them

# Custom tag (application-defined)
person: !person
  name: Alice
  age: 30

# Tag with arguments
color: !color rgb(255, 0, 0)
point: !point [10, 20]

# Library-specific tags (PyYAML example)
# python/object/apply:module.func args
sorted_set: !!python/object/apply:sorted
  args:
    - [3, 1, 2]

# Ruby-specific (Psych)
# !ruby/object:ClassName

# Custom tags require custom constructors in code.
# Unknown tags usually cause errors in safe loaders.

로컬 및 축자 태그

!prefix는 로컬 태그(애플리케이션 정의)용이고, !!는 yaml.org 전역 태그의 단축이며, !<uri>는 축자(해석 없음), !prefix!short는 간결성을 위해 %TAG로 선언한 접두사를 씁니다. 로컬 태그가 가장 흔하고 축자 태그는 도구 간 스키마에 중요합니다.

yaml
# ! prefix — local tag (application-specific, no URI)
data: !myapp/data
  value: 42

# !! prefix — global built-in tag (resolved to yaml.org)
str: !!str hello

# !<full-uri> — verbatim tag (exact URI, no resolution)
binary: !<tag:example.com,2024:binary> "data"

# !tag!short — tag with prefix (resolved via %TAG directive)
%TAG !e! tag:example.com,2024:
data: !e!custom value
# resolves to tag:example.com,2024:custom

# %TAG directives declare prefixes
%TAG !yaml! tag:yaml.org,2002:
value: !yaml!str 42   # same as !!str

# Local tags are most common in app-specific YAML
# Verbatim tags are useful for cross-tool interoperability

태그 해석

태그 해석은 스키마에 따라 다릅니다. Failsafe(최소)는 태그가 없으면 모든 것을 문자열로 취급합니다. JSON 스키마는 int/float/bool/null을 추가합니다. Core 스키마(YAML 1.2 기본)는 더 관대한 매칭으로 JSON을 확장합니다. 명시적 태그(!!)는 항상 스키마 해석을 덮어씁니다.

yaml
# Tags are resolved by the schema (Core, JSON, Failsafe)
# Without explicit tags, the schema infers types

# Failsafe schema — only str, map, seq (no inference)
# Everything is a string unless tagged
failsafe_value: 42       # str "42"
failsafe_tagged: !!int 42  # int 42

# JSON schema — str, int, float, bool, null, map, seq
json_value: 42           # int
json_str: "42"           # str

# Core schema (default for YAML 1.2) — like JSON but
# with more lenient parsing (yes/no not bool, etc.)
core_value: 42           # int
core_bool: true          # bool
core_str: hello          # str

# Explicit tags override schema resolution
forced: !!str true       # str "true" (even in Core)

애플리케이션별 태그

애플리케이션별 태그로 도메인 객체(Money, DateRange 등)를 YAML에 임베드할 수 있습니다. 로더가 각 태그의 생성자를 등록해야 합니다. 항상 알 수 없는 태그를 기본 거부하는 안전 로더를 사용하고 신뢰할 수 없는 YAML이 임의 생성자를 호출하게 하지 마세요(고전적 역직렬화 취약점).

yaml
# Define your own tags for domain objects
# Example: a config loader for a custom app

# Tag a node as a "Money" object
price: !money "USD 19.99"

# Tag a node as a "DateRange"
range: !dateRange
  start: 2024-01-01
  end: 2024-12-31

# Tag nodes for custom parsing/validation
settings: !strict
  host: localhost
  port: 8080

# PyYAML example: register a constructor
# class MoneyLoader:
#     def __init__(self, value):
#         self.currency, self.amount = value.split()
#         self.amount = float(self.amount)
#
# yaml.add_constructor('!money', lambda l, n:
#     MoneyLoader(l.construct_scalar(n)))

# Safe loaders reject unknown tags — opt-in explicitly
# to avoid processing untrusted input with side effects.
09

문서 표시자와 지시문

단일 문서

단일 YAML 문서는 표시자 없이도 잘 동작합니다. 맨 앞의 ---는 '이것은 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()이나 동등한 함수로 문서를 반복하세요.

yaml
# 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에서는 드물지만 프로그램 출력에서는 흔합니다.

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 이중 모드)에 의존합니다.

yaml
# 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 로그, 정적 사이트 생성기(프런트 매터 + 콘텐츠)도 스트림을 씁니다. 각 문서는 독립적이고 자체 지시문을 가질 수 있습니다.

yaml
# Kubernetes multi-object file
---
apiVersion: v1
kind: Namespace
metadata:
  name: production
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: production
spec:
  replicas: 3
---
apiVersion: v1
kind: Service
metadata:
  name: api
  namespace: production
spec:
  ports:
    - port: 80

# Helm chart templates: stream of objects
# CI logs: one event per document
# Static site generator: front matter + body

경계 함정

0열에서 ---로 시작하는 줄은 블록 스칼라 밖에서 항상 문서 구분자입니다. 블록 스칼라(|, >) 안에서 ---는 리터럴 내용입니다. 값에 0열 ---를 포함하려면 블록을 들여쓰거나 먼저 ...로 문서를 끝내세요. 같은 줄에 내용이 있는 ---는 구분자가 아니라 문서 시작 표시자입니다.

yaml
# A line starting with --- is ALWAYS a document separator
# (when at column 0). This can surprise you:

---
script: |
  echo hello
  ---  # this is INSIDE the block scalar — safe
next: value

# But this is NOT safe:
---
content: |
  line1
---
mistaken: this is a NEW document, not part of content!

# Inside block scalars, --- is literal (good).
# Outside, --- at column 0 always separates documents.

# Workaround for content that must contain --- at col 0:
# indent the block, or use ... to end the doc first.

# Also: a bare --- line with content on the same line
# is the document start marker, NOT a separator
--- key: value   # this is one document
10

플로우 스타일

플로우 시퀀스

플로우 시퀀스는 [ ]를 쓰며 JSON 배열처럼 동작합니다. 안의 공백과 줄바꿈은 유연합니다. JSON과 달리 후행 쉼표를 허용하지 않습니다. 짧고 밀집한 목록에 유용합니다. 특수 문자(쉼표, 대괄호, 콜론)가 있는 항목은 따옴표로 감싸세요.

yaml
# Flow sequences use [item1, item2, ...]
numbers: [1, 2, 3]
names: [Alice, Bob, Charlie]

# Empty
empty: []

# Nested flow sequences
matrix: [[1, 2], [3, 4]]

# Flow sequence of mappings
points: [{x: 1, y: 2}, {x: 3, y: 4}]

# Multi-line flow sequence (whitespace is flexible)
long: [
  alpha,
  beta,
  gamma
]

# Quoting inside flow
mixed: ["hello", 'world', 42, true]

# NO trailing comma
bad: [1, 2, 3,]   # parse error

플로우 매핑

플로우 매핑은 { }를 쓰며 JSON 객체처럼 동작합니다. 키에 특수 문자가 있으면 따옴표로 감쌀 수 있습니다. 공백은 유연합니다. 후행 쉼표는 금지됩니다(JSON과 다름). 짧고 밀집한 데이터에는 플로우 매핑을, 큰 구조에는 블록 스타일이 더 읽기 쉽습니다.

yaml
# Flow mappings use {key: value, ...}
point: {x: 10, y: 20}
config: {host: localhost, port: 8080}

# Empty mapping
empty: {}

# Nested flow mappings
nested: {a: {b: {c: value}}}

# Quoted keys (needed for special chars)
quoted: {"key with space": value, "weird:key": 1}

# Multi-line flow mapping
config: {
  host: localhost,
  port: 8080,
  debug: true
}

# Flow mapping with flow sequence value
mixed: {nums: [1, 2, 3], name: test}

# NO trailing comma
bad: {a: 1, b: 2,}   # parse error

플로우와 블록 혼합

플로우와 블록 스타일은 문서 안에서 자유롭게 섞을 수 있습니다. 실용 규칙: 구조 요소에는 블록 스타일(들여쓰기로 가독성 향상), 짧은 인라인 값(스칼라 목록, 작은 맵)에는 플로우 스타일을 사용하세요. 깊게 중첩된 플로우는 금방 읽기 어려워지므로 피하세요.

yaml
# Mix flow and block styles freely
config:
  name: myapp
  ports: [80, 443]        # flow sequence in block mapping
  endpoints: {api: /v1, web: /}  # flow mapping in block

# Block inside flow (less common but valid)
flow_with_block: [{name: Alice, roles: [admin, user]}, {name: Bob}]

# Flow at top level
[top, level, flow]

# Block at top level
- block
- sequence

# Pragmatic rule:
# - Block for structure (readability)
# - Flow for short inline values
# - Avoid deeply nested flow — it becomes unreadable

중첩 플로우

플로우 스타일은 임의 깊이로 중첩될 수 있지만 수준마다 대괄호/중괄호가 늘어 읽기 어려워집니다. 1-2수준 중첩 후에는 가독성을 위해 블록 스타일로 전환하세요. 깊게 중첩된 플로우의 블록 등가물이 인간 유지보수자에게 거의 항상 더 명확합니다.

yaml
# Flow can nest arbitrarily
data: {users: [{name: Alice, tags: [a, b]}, {name: Bob}]}

# Equivalent block:
# data:
#   users:
#     - name: Alice
#       tags:
#         - a
#         - b
#     - name: Bob

# Multi-line nested flow (rare but valid)
matrix: {
  rows: [
    [1, 2, 3],
    [4, 5, 6]
  ],
  cols: 3
}

# Recommendation: switch to block style after 1-2 levels
# of nesting — flow becomes a "wall of brackets".

플로우 스타일을 쓸 때

짧은 스칼라 목록, 작은 조회 맵, 한 줄 레코드, JSON 호환 출력에 플로우 스타일을 사용하세요. 긴 목록(스캔 어려움), 깊게 중첩된 구조(대괄호의 벽), 인라인 주석이 필요한 것에는 플로우를 피하세요. 확신이 없으면 가독성을 위해 블록 스타일을 선호하세요.

yaml
# Good uses of flow style:

# 1. Short lists of scalars
ports: [80, 443, 8080]
colors: [red, green, blue]

# 2. Small lookup maps
codes: {200: OK, 404: NotFound, 500: Error}

# 3. Single-line records in a sequence
coordinates:
  - {x: 1, y: 2}
  - {x: 3, y: 4}
  - {x: 5, y: 6}

# 4. JSON-compatible output (flow is JSON-compatible)

# Bad uses of flow style:

# 1. Long lists (use block)
#   ports: [80, 443, 8080, 8443, 9000, 9090, 9091, ...]  # hard to read

# 2. Deeply nested (use block)
#   {a: {b: {c: {d: {e: value}}}}}  # unreadable

# 3. Anything with comments (flow doesn't allow inline comments well)

플로우 스타일 주의점

플로우 스타일 주의점: 특수 문자(쉼표, 콜론, 대괄호)는 따옴표가 필요하고, 후행 쉼표가 없으며, 주석이 어색하고, |나 > 블록 스칼라를 쓸 수 없으며(큰따옴표 문자열에 \n 사용), 한 줄 변경의 diff가 어렵습니다. 버전 관리되는 설정에는 블록 스타일이 더 친절합니다.

yaml
# Caveat 1: special characters need quotes in flow
flow: [a, b, "c,d", "d:e"]   # commas and colons need quoting
block:
  - a
  - b
  - c,d      # no quotes needed in block style
  - d:e      # no quotes needed in block style

# Caveat 2: no trailing commas
bad: [1, 2, 3,]   # error

# Caveat 3: comments are awkward in flow
config: {
  host: localhost,  # comment allowed but clunky
  port: 8080
}

# Caveat 4: flow style has no multi-line strings
# (no | or > inside flow)
# You can use \n escapes in double quotes:
text: "line1\nline2"

# Caveat 5: flow is harder to diff in version control
# (one-line changes vs whole-block changes)
11

YAML과 JSON 변환

JSON은 유효한 YAML

YAML 1.2는 JSON이 엄격한 부분 집합이 되도록 설계되어 모든 JSON 문서가 유효한 YAML입니다. 대부분의 YAML 파서가 JSON을 잘 읽습니다. 반대는 성립하지 않습니다. 주석, 앵커, 다중 문서 스트림, 블록 스칼라 같은 YAML 기능은 유효한 JSON이 아닙니다.

yaml
# JSON is a strict subset of YAML 1.2
# Any JSON file is valid YAML

# This is valid YAML (it's JSON):
{"name": "Alice", "age": 30, "hobbies": ["a", "b"]}

# So is this multi-line JSON:
{
  "name": "Alice",
  "age": 30,
  "hobbies": ["a", "b"]
}

# Parsers usually accept JSON files as YAML
# Python: yaml.safe_load(json_string)  # works
# JS:     YAML.load(json_string)       # works
# Go:     yaml.Unmarshal(json_bytes, &v)  # works (yaml.v3)

# But the reverse is NOT always true:
# YAML with comments, anchors, multi-docs is NOT valid JSON

동등한 표현

JSON, YAML 블록, YAML 플로우는 같은 데이터를 표현할 수 있습니다. JSON이 가장 이식성이 좋고(모든 언어에 JSON 파서가 있음) YAML 블록이 사람에게 가장 읽기 쉬우며 YAML 플로우는 압축된 중간 지대입니다. 대상(도구는 JSON, 사람은 YAML 블록)에 따라 선택하세요.

yaml
# JSON:
{"name": "Alice", "age": 30, "hobbies": ["a", "b"]}

# YAML block:
name: Alice
age: 30
hobbies:
  - a
  - b

# YAML flow (closest to JSON):
{name: Alice, age: 30, hobbies: [a, b]}

# YAML with quotes (JSON-compatible):
{"name": "Alice", "age": 30, "hobbies": ["a", "b"]}

# All four parse to the same data structure.
# Pick the style that fits your use case:
# - JSON for interop and strict tools
# - YAML block for human-edited config
# - YAML flow for compact inline data

JSON to YAML 변환

JSON을 파싱한 뒤 default_flow_style=False(블록 스타일)로 YAML 덤프해 변환합니다. JSON의 필수 따옴표는 YAML이 필요 없는 곳에서 제거됩니다. 숫자/불리언처럼 보이는 키는 문자열 타입을 보존하려고 YAML에서 따옴표가 필요할 수 있으니 주의하세요.

yaml
# Convert JSON to YAML using a parser
# Python:
# import json, yaml
# data = json.loads(json_string)
# yaml_str = yaml.safe_dump(data, default_flow_style=False, sort_keys=False)
#
# JS:
# const data = JSON.parse(jsonString)
# const yamlStr = yaml.dump(data)

# Example input JSON:
# {"server": {"host": "localhost", "port": 8080}, "debug": true}

# Output YAML:
# server:
#   host: localhost
#   port: 8080
# debug: true

# Conversion considerations:
# - JSON keys are always quoted -> YAML usually unquotes them
# - JSON arrays -> YAML block sequences (with default_flow_style=False)
# - JSON strings with special chars may need quoting
# - JSON null -> YAML null (or ~)
# - JSON booleans/numbers preserved

YAML to JSON 변환

YAML을 파싱한 뒤 JSON으로 직렬화해 변환합니다. 주의: 주석과 태그는 사라지고 앵커는 평범한 복사본으로 확장되며 다중 문서 스트림은 JSON 배열이 되어야 하고 YAML 날짜는 문자열이 될 수 있습니다. yq 같은 도구가 명령줄에서 이를 쉽게 합니다.

yaml
# Convert YAML to JSON
# Python:
# import json, yaml
# data = yaml.safe_load(yaml_string)
# json_str = json.dumps(data, indent=2)

# JS:
# const data = yaml.load(yamlString)
# const jsonStr = JSON.stringify(data, null, 2)

# Command-line tools:
# yq -o=json '.config' file.yaml        # mikefarah/yq
# ruby -ryaml -rjson -e 'puts JSON.generate(YAML.load(STDIN.read))' < file.yaml
# python -c 'import json,sys,yaml; print(json.dumps(yaml.safe_load(sys.stdin)))'

# Caveats when converting YAML to JSON:
# - YAML comments are LOST (JSON has no comments)
# - YAML anchors are EXPANDED to plain copies
# - YAML multi-doc streams become a JSON array (or fail)
# - YAML tags (!!) are lost or cause errors
# - YAML dates may become strings (JSON has no date type)

JSON 호환 부분 집합

YAML의 JSON 호환 부분 집합은 주석, 앵커, 다중 문서, 태그, 블록 스칼라, 다른 타입처럼 보이는 일반 문자열을 피합니다. 이 부분 집합에 머물면 JSON으로 깔끔한 왕복이 보장됩니다. YAML과 JSON 소비자가 같은 데이터를 읽거나 엄격한 타입 보존이 중요할 때 유용합니다.

yaml
# To produce YAML that round-trips to JSON cleanly,
# stay within the JSON-compatible subset:

# 1. No comments
# 2. No anchors/aliases
# 3. No multi-doc streams
# 4. No tags
# 5. No block scalars (|, >) — use \n in double-quoted strings
# 6. Quote all string keys (JSON requires this)
# 7. No plain strings that look like other types

# JSON-compatible YAML:
{"name": "Alice", "age": 30, "active": true}
{"items": ["a", "b", "c"]}
{"nested": {"key": "value"}}

# Useful when you need both YAML and JSON consumers
# for the same data, or want strict type preservation.

# Many YAML dumpers have a "json-compatible" mode.

왕복 고려사항

YAML 왕복(파싱 후 덤프)은 주석, 앵커 이름, 키 순서, 인용 스타일, 서식을 잃는 경우가 많습니다. ruamel.yaml(Python)은 주석과 순서를 보존하는 왕복 모드가 있습니다. 사람이 편집하는 설정을 덤퍼 출력으로 무턱대고 덮어쓰지 말고 먼저 주의 깊게 diff하세요.

yaml
# Round-trip: YAML -> parse -> dump -> YAML
# Information that may be LOST:
# - Comments (most dumpers drop them)
# - Anchor names (dumpers may re-create or expand)
# - Key order (some dumpers sort keys)
# - Quoting style (dumpers choose their own)
# - Flow vs block style (dumpers usually pick one)
# - Whitespace and indentation amount
# - Multi-document structure (sometimes)
# - Tag prefixes and %TAG directives

# Tools that preserve style:
# - ruamel.yaml (Python): round-trip mode preserves comments/order
# - yaml.v3 (Go): preserves key order
# - prettier with yaml plugin: normalizes formatting

# For config files where humans edit:
# - Use ruamel.yaml round-trip mode
# - Or accept that dumps are "normalized"
# - Never overwrite human-edited files with dumper output
#   without diffing carefully
12

YAML 스키마

Failsafe 스키마

Failsafe 스키마는 가장 보수적이라 str, map, seq만 인식합니다. 명시적 태그가 없으면 모든 스칼라는 문자열입니다. 신뢰할 수 없는 입력(암시적 강제 변환 놀라움 없음)이나 커스텀 스키마의 기반으로 유용합니다. 대부분의 운영 로더는 약간 더 풍부한 스키마를 씁니다.

yaml
# Failsafe schema — the most conservative
# Recognizes ONLY three types: str, map, seq
# Everything else is a string

# Under Failsafe:
value: 42           # str "42" (NOT int)
flag: true          # str "true" (NOT bool)
empty: null         # str "null" (NOT null)
date: 2024-01-01    # str "2024-01-01" (NOT date)

# Use explicit tags to get other types
int_value: !!int 42
bool_value: !!bool true
null_value: !!null null

# When to use Failsafe:
# - Untrusted input (no implicit type coercion)
# - When you want strings only
# - As a base for custom schemas

# PyYAML: SafeLoader uses a schema close to Failsafe
# but with int/float/bool/null inference.

JSON 스키마

JSON 스키마는 JSON 타입 시스템과 정확히 일치합니다: str, int, float, bool, null, map, seq. Core 스키마보다 엄격해 8진/2진 리터럴, 밑줄 구분자, true/false 외 불리언, 날짜 추론이 없습니다. JSON 상호운용이나 엄격한 타입 동작에 사용하세요.

yaml
# JSON schema — same type system as JSON
# Recognizes: str, int, float, bool, null, map, seq

# Under JSON schema:
int: 42             # int
float: 3.14         # float
str: hello          # str
bool: true          # bool
null_val: null      # null
list: [1, 2, 3]     # seq
map: {a: 1}         # map

# Differences from Core schema:
# - Stricter number parsing (no 0o octal, no _ separators)
# - Booleans are only true/false (no yes/no)
# - No date/timestamp inference

# When to use JSON schema:
# - Interop with JSON tools
# - Strict type behavior
# - When you want JSON's type semantics

Core 스키마

Core 스키마는 YAML 1.2 기본입니다. 관대한 파싱으로 JSON을 확장합니다: 16진(0x), 8진(0o), 2진(0b), 숫자 밑줄, .inf/.nan 부동소수. 불리언은 true/false만(yes/no 아님)입니다. 날짜는 문자열(추론 없음)입니다. 대부분의 최신 파서는 Core나 1.1 호환 변형을 기본으로 씁니다.

yaml
# Core schema — the DEFAULT for YAML 1.2
# Extends JSON schema with more lenient scalar resolution

# Under Core schema:
int: 42             # int
neg: -17            # int
hex: 0xFF           # int (255)
oct: 0o17           # int (15)  [YAML 1.2 syntax]
bin: 0b1010         # int (10)
float: 3.14         # float
exp: 1.0e+3         # float
inf: .inf           # float
nan: .nan           # float
bool: true          # bool (only true/false, not yes/no)
null: null          # null (also ~, empty)
str: hello          # str
date: 2024-01-01    # str (Core does NOT infer dates)

# Differences from YAML 1.1:
# - yes/no/on/off are STRINGS (not booleans)
# - 017 is a string (octal is 0o17 in 1.2)
# - Dates are strings (no implicit inference)

# Most modern parsers default to Core or close to it.

YAML 1.1 vs 1.2

YAML 1.1(PyYAML 기본)은 yes/no/on/off를 불리언으로, 앞에 0이 붙은 숫자를 8진수로 취급해 유명한 버그 원인이 됩니다(노르웨이 'no' → false). YAML 1.2(현재 명세)는 불리언을 true/false로 제한하고 8진수에 0o를 씁니다. 항상 파서 기본값을 확인하고 모호한 문자열을 따옴표로 감싸세요.

yaml
# YAML 1.1 (older, used by PyYAML by default)
bool_1_1: yes       # true (yes/no/on/off are booleans)
octal_1_1: 017      # 15 (leading 0 = octal)
sexagesimal: 1:30   # 90 (base-60!) - obscure feature

# YAML 1.2 (current spec)
bool_1_2: yes       # str "yes" (only true/false are bool)
octal_1_2: 0o17     # 15 (explicit 0o prefix)
no_sexagesimal: 1:30 # str "1:30"

# Practical impact:
# - "no" (Norway) becomes False in PyYAML (1.1)
# - "010" becomes 8 in PyYAML, "010" in 1.2
# - "on"/"off" become True/False in 1.1, strings in 1.2

# PyYAML: defaults to 1.1 behavior
# ruamel.yaml: defaults to 1.2 (with 1.1 compatibility options)
# js-yaml: defaults to 1.1 with 1.2 options
# Go yaml.v3: defaults to 1.2-ish

# Always check your parser's default schema!

타입 해석 차이

YAML 1.1과 1.2 파서는 타입 해석이 다릅니다: yes/no/on/off, 앞자리 0 숫자, 60진 리터럴이 다르게 파싱됩니다. 모호한 문자열을 따옴표로 감싸고, %YAML로 버전을 고정하며, 명시적 태그를 쓰고, 모든 대상 파서에서 테스트해 완화하세요.

yaml
# Same YAML, different parsers, different types:
value: yes

# PyYAML (1.1):        True (bool)
# js-yaml (1.1):       true (bool)
# ruamel (1.2):        "yes" (str)
# Go yaml.v3 (1.2):    "yes" (str)
# Strict 1.2:          "yes" (str)

value: 010

# PyYAML (1.1):        8 (int, octal)
# ruamel (1.2):        "010" (str)
# Go yaml.v3 (1.2):    "010" (str)

value: 1.0

# All:                 1.0 (float) - consistent

value: true

# All:                 true (bool) - consistent

# Mitigation strategies:
# 1. Quote strings that look like other types
# 2. Pin the YAML version with %YAML 1.2
# 3. Use explicit tags (!!) for critical values
# 4. Test against all target parsers

스키마 선택

사용 사례로 스키마를 선택하세요: 새 프로젝트에는 1.2 Core(예측 가능), PyYAML 상호운용에는 1.1(또는 모호한 문자열 인용), 신뢰할 수 없는 입력에는 Failsafe/JSON, JSON 상호운용에는 JSON 스키마. 설정 파일에는 1.2 Core와 모호한 문자열("no", "010" 등) 인용이 가장 안전한 조합입니다.

yaml
# Recommendations for choosing a schema:

# 1. For NEW projects: use YAML 1.2 Core schema
#    - More predictable (no yes/no surprises)
#    - Modern parsers support it
#    - ruamel.yaml, Go yaml.v3 default to it

# 2. For INTEROP with existing PyYAML code:
#    - Either accept 1.1 semantics
#    - Or use ruamel.yaml with 1.2 + preserve 1.1 features
#    - Quote all ambiguous strings explicitly

# 3. For UNTRUSTED input: use Failsafe or JSON schema
#    - No implicit type coercion
#    - Smaller attack surface
#    - Predictable behavior

# 4. For CONFIG FILES: use 1.2 Core + quote ambiguous strings
#    - "no", "yes", "on", "off", "010", "1.0" should be quoted
#    - Document your schema choice
#    - Lint with yamllint

# 5. For JSON INTEROP: use JSON schema
#    - Same types as JSON
#    - Round-trips cleanly
13

YAML 린트와 검증

yamllint

yamllint는 표준 YAML 린터(Python)입니다. 구문 오류, 들여쓰기 문제, 뒤 공백, 문서 표시자 누락 등을 잡습니다. CI와 pre-commit 훅에서 사용해 YAML 문제를 일찍 잡으세요. 엄격 모드(-s)는 경고를 오류로 취급합니다.

yaml
# yamllint is the standard YAML linter
# Install: pip install yamllint

# Lint a file
# yamllint config.yaml

# Lint with strict mode (warnings = errors)
# yamllint -s config.yaml

# Output example:
# config.yaml
#   3:4       error    mapping values are not allowed here
#   5:1       error    syntax error: found character '	' that cannot start any token
#   8:3       warning  missing document start "---"
#   12:5      warning  comment is not indented like content

# Lint multiple files
# yamllint file1.yaml file2.yaml file3.yaml

# Lint a directory (recursive)
# yamllint -d path/to/dir

# Read from stdin
# cat config.yaml | yamllint -

린트 설정

.yamllint.yml로 yamllint를 설정하세요. 프로필(default 또는 strict)을 확장한 뒤 개별 규칙(들여쓰기, 줄 길이, 인용 스타일, 주석, 뒤 공백, 문서 표시자)을 덮어쓰세요. 팀 스타일에 맞게 조정하고 CI에서 실행해 일관되게 강제하세요.

yaml
# .yamllint.yml — configuration file for yamllint
# Place in project root or ~/.config/yamllint/config

# Use a built-in profile
extends: default

# Or use a stricter profile
# extends: strict

# Override specific rules
rules:
  # Require document start marker
  document-start: disable
  # Enforce 2-space indentation
  indentation:
    spaces: 2
    indent-sequences: true
  # Max line length
  line-length:
    max: 120
    allow-non-breakable-words: true
  # Disallow trailing spaces
  trailing-spaces: enable
  # Require consistent quoting
  quoted-strings:
    quote-type: double
    required: only-when-needed
  # Disallow comments without space before #
  comments:
    require-starting-space: true
    min-spaces-from-content: 1

흔한 구문 오류

흔한 YAML 오류: 들여쓰기에 탭 사용(공백만 허용), 뒤 공백 없는 콜론, 콜론이 있는 따옴표 없는 문자열(매핑으로 파싱됨), 플로우 스타일의 후행 쉼표, 일관되지 않은 들여쓰기, 중복 키. 린터가 이 모두를 자동으로 잡습니다.

yaml
# Error: tab characters for indentation
# bad:
# 	key: value   <- tab not allowed
# Fix: use spaces only

# Error: colon without space
# bad:  key:value
# good: key: value

# Error: unquoted special characters
# bad:  url: http://example.com:8080   <- parsed as mapping
# good: url: "http://example.com:8080"

# Error: trailing comma in flow
# bad:  list: [1, 2, 3,]
# good: list: [1, 2, 3]

# Error: inconsistent indentation
# bad:
#   key1: value
#    key2: value   <- one extra space
# good:
#   key1: value
#   key2: value

# Error: duplicate keys (some parsers warn)
# bad:
#   key: first
#   key: second
# good: rename one

탭 vs 공백 오류

YAML 구조 들여쓰기에는 탭이 엄격히 금지되며 파싱 오류의 1위 원인입니다. 문자열 값(블록 스칼라, 따옴표 문자열) 안의 탭은 괜찮습니다. 편집기에서 YAML 파일에 공백(expandtab)을 쓰도록 설정하세요. grep -P '\t'로 문제 줄을 찾으세요.

yaml
# YAML FORBIDS tabs for indentation.
# This is the #1 cause of YAML parse errors.

# Symptom: parser error like
# "found character '\t' that cannot start any token"
# or "while scanning for the next token, found tab"

# Tabs are allowed INSIDE string values:
script: |
  #!/bin/bash
  if [ -f file ]; then   # this is fine (literal content)
  \techo found           # \t inside block scalar is OK

# But tabs for STRUCTURAL indentation are forbidden:
# bad:
# services:
# \tweb:
# \t\timage: nginx

# Fix: convert tabs to spaces
# Configure your editor to use spaces for YAML files
# VS Code: "editor.insertSpaces": true, "editor.tabSize": 2
# Vim: set expandtab shiftwidth=2

# Detect tabs:
# grep -P '\t' file.yaml   (finds offending lines)

중복 키 탐지

매핑의 중복 키는 권장되지 않고 흔한 버그 원인입니다(조용한 마지막 우선 덮어쓰기). yamllint가 key-duplicates 규칙(기본 활성)으로 탐지합니다. 흔한 원인: 복사-붙여넣기 오류와 잘못된 병합 충돌 해결. CI에서 항상 린트해 일찍 잡으세요.

yaml
# Duplicate keys are technically discouraged
# but YAML 1.2 doesn't strictly forbid them.
# Behavior varies by parser (usually last-wins).

config:
  host: localhost
  port: 8080
  host: prod.example.com   # silent override!

# yamllint catches these:
#   4:3  error  duplication of key "host" in mapping

# Enable in .yamllint.yml:
# rules:
#   key-duplicates: enable

# Other tools that detect duplicates:
# - kubeval (for Kubernetes YAML)
# - yq (programmatic checks)
# - Custom schema validation (JSON Schema)

# Common cause: copy-paste errors, merge conflicts
# resolved incorrectly. Always lint in CI to catch.

스키마 검증

JSON Schema로 YAML 구조를 검증하세요(YAML이 JSON 상위 집합이라 동작). Kubernetes에는 kubeval이나 kubectl --dry-run을 사용하세요. 일반 설정에는 yamllint(구문/스타일)와 jsonschema(구조) 또는 Cue(스키마 언어)를 사용하세요. 검증을 pre-commit 훅과 CI에 연결하세요.

yaml
# Validate YAML against a JSON Schema
# (JSON Schema works on YAML since YAML is a JSON superset)

# Python example with jsonschema + PyYAML:
# import json, yaml, jsonschema
# with open('schema.json') as f: schema = json.load(f)
# with open('config.yaml') as f: doc = yaml.safe_load(f)
# jsonschema.validate(doc, schema)

# Tools for Kubernetes YAML:
# kubeval            - validate against K8s schemas
# kubectl apply --dry-run=client -f file.yaml
# conftest           - policy-based validation (OPA)

# Tools for general YAML:
# yamllint           - syntax + style
# jsonschema-cli     - JSON Schema validation
# cue                - schema + validation language
# dataladen          - config validation

# Pre-commit hook example (.pre-commit-config.yaml):
# repos:
#   - repo: https://github.com/adrienverge/yamllint
#     rev: v1.32.0
#     hooks:
#       - id: yamllint
#         args: [-s]
14

Docker Compose YAML

서비스 정의

Docker Compose 파일은 다중 컨테이너 앱을 정의합니다. 최상위 키는 version, services, volumes, networks, configs, secrets입니다. 각 서비스는 image/build, ports, volumes, environment, depends_on, restart 정책을 정의합니다. 최상위에 선언한 볼륨은 이름이 있고 지속됩니다.

yaml
# docker-compose.yml — multi-container apps
version: "3.9"   # compose file format version

services:
  web:
    image: nginx:1.25
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./html:/usr/share/nginx/html:ro
    restart: unless-stopped
    depends_on:
      - api

  api:
    build:
      context: ./api
      dockerfile: Dockerfile
    environment:
      - NODE_ENV=production
      - DB_URL=postgres://db:5432/app
    ports:
      - "8080:8080"
    restart: always

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - db_data:/var/lib/postgresql/data
    restart: always

volumes:
  db_data:

볼륨과 네트워크

Compose 볼륨은 바인드 마운트(host:container), 이름 있는 볼륨(최상위 volumes에 선언), 익명 볼륨입니다. :ro 접미사는 마운트를 읽기 전용으로 만듭니다. 네트워크는 서비스를 격리하고 internal: true는 외부 접근을 막습니다. 이름 있는 볼륨은 컨테이너 재생성 간 데이터를 유지합니다.

yaml
services:
  web:
    image: nginx
    volumes:
      # Bind mount: host:container
      - ./html:/usr/share/nginx/html:ro
      # Named volume: name:container
      - shared_data:/data
      # Anonymous volume
      - /tmp/cache
    networks:
      - frontend
      - backend

  db:
    image: postgres
    volumes:
      - db_data:/var/lib/postgresql/data
    networks:
      - backend

volumes:
  db_data:
    driver: local
  shared_data:
    driver: nfs
    driver_opts:
      type: nfs
      device: ":/path/to/share"

networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true   # no external access

환경 변수

Compose는 세 가지 환경 변수 스타일을 지원합니다: 리스트(KEY=value), 맵(KEY: value), env_file. ${VAR}는 파싱 시 호스트 셸이나 .env 파일에서 보간되고 ${VAR:-default}는 기본값을 제공합니다. 리터럴 $는 $$로 이스케이프하세요. 프로젝트 루트의 .env 파일은 자동 로드됩니다.

yaml
services:
  api:
    image: myapi
    # Method 1: list of KEY=value
    environment:
      - NODE_ENV=production
      - LOG_LEVEL=info
    # Method 2: map (cleaner)
    environment:
      NODE_ENV: production
      LOG_LEVEL: info
    # Method 3: file
    env_file:
      - .env
      - .env.production
    # Interpolation from host environment
    environment:
      - API_KEY=${API_KEY}     # from shell
      - PORT=${PORT:-8080}      # default 8080

# .env file (auto-loaded by docker compose):
# API_KEY=abc123
# PORT=8080
# DB_URL=postgres://...

# Compose substitutes ${VAR} from host shell or .env
# Use $$ to escape (literal $):
# - TOKEN=price_$$5   # produces price_$5

의존성, 헬스체크, 재시작

condition: service_healthy가 있는 depends_on은 의존성의 헬스체크가 통과한 뒤 시작합니다. 헬스체크는 test(CMD 또는 CMD-SHELL), interval, timeout, retries, start_period를 씁니다. 재시작 정책: no, always, unless-stopped(재부팅 후에도 유지하되 수동 중지는 존중), on-failure.

yaml
services:
  api:
    image: myapi
    depends_on:
      db:
        condition: service_healthy   # wait for db healthy
      redis:
        condition: service_started
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s

  db:
    image: postgres
    restart: always
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

# restart policies:
# no              - never restart (default)
# always          - always restart on stop
# unless-stopped  - restart unless manually stopped
# on-failure      - restart only on non-zero exit

오버라이드 파일

Compose는 오버라이드 파일을 기본 위에 병합합니다. docker-compose.override.yml은 자동 적용됩니다. 매핑은 깊이 병합되고(오버라이드 우선) 시퀀스는 보통 대체됩니다(추가 아님). ports/volumes에 주의하세요. 환경별 설정에는 -f 플래그로 명시적 파일 순서를 지정하세요.

yaml
# docker-compose.yml — base
services:
  web:
    image: nginx
    ports:
      - "80:80"
    environment:
      - ENV=base

# docker-compose.override.yml — auto-applied on top
# (loaded automatically by 'docker compose up')
services:
  web:
    ports:
      - "8080:80"      # overrides "80:80"
    environment:
      - DEBUG=true     # added
      - ENV=override   # overrides ENV=base
    volumes:
      - ./dev.conf:/etc/nginx/conf.d/default.conf

# Multiple override files (-f flag):
# docker compose -f compose.yml -f compose.prod.yml -f compose.secrets.yml up

# Merge rules:
# - mappings: deep-merged (overrides win, others kept)
# - sequences: usually REPLACED (not appended) —
#   ports/depends_on/volumes are exceptions in some versions

# Use -f to specify explicit file order

프로필과 Compose 기능

프로필은 --profile 플래그로 서비스(예: debug, test, ci)를 선택적으로 켜게 합니다. 다른 v3 기능: init(적절한 PID 1 시그널 처리), extends(다른 서비스 상속), configs와 secrets(파일로 마운트), deploy(Swarm 배치/복제본/리소스). 프로필은 여러 환경에 하나의 compose 파일을 유지하는 데 좋습니다.

yaml
# Profiles — opt-in services
services:
  web:
    image: nginx
    # no profile: always started

  debug:
    image: busybox
    profiles: ["debug"]   # only with --profile debug

  loadtest:
    image: locust
    profiles: ["test", "ci"]

# Enable a profile:
# docker compose --profile debug up
# docker compose --profile test --profile ci up

# Compose file format features (v3.9+):
# - deploy: placement, replicas, resources (Swarm-only in v3)
# - configs: external config files
# - secrets: mounted secret files
# - extends: inherit from another service
# - init: run tini as PID 1

services:
  worker:
    image: worker
    init: true   # proper signal handling
    extends:
      service: base   # inherit fields
    configs:
      - config1
    secrets:
      - api_key

configs:
  config1:
    file: ./config.toml
secrets:
  api_key:
    file: ./api_key.txt
15

Kubernetes YAML

객체 구조

모든 Kubernetes 객체에는 apiVersion, kind, metadata, spec이 있습니다. apiVersion은 group/version(예: apps/v1, 코어는 v1)입니다. metadata에는 name, namespace, labels, annotations가 있습니다. spec은 원하는 상태이며 Kubernetes가 현실을 spec에 맞추려 합니다. status는 시스템이 설정합니다.

yaml
# Every Kubernetes object has the same 4 top-level fields
apiVersion: apps/v1        # API group + version
kind: Deployment           # object type
metadata:                  # identity
  name: my-app
  namespace: production
  labels:
    app: my-app
    tier: backend
  annotations:
    deployment.kubernetes.io/revision: "1"
spec:                      # desired state
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:1.0.0
          ports:
            - containerPort: 8080

# apiVersion + kind + metadata + spec is the universal shape
# (some objects use status too, but you don't set it)

레이블과 셀렉터

레이블은 객체를 식별하고 그룹화하며 셀렉터는 레이블로 질의합니다. 동등 기반(key=value)과 집합 기반(In, NotIn, Exists, DoesNotExist) 셀렉터를 모두 지원합니다. 어노테이션은 식별용이 아닌 메타데이터(설명, 연락처, 도구 설정)를 담습니다. 레이블은 선택용, 어노테이션은 추가 정보용입니다.

yaml
# Labels — identify and group objects
metadata:
  labels:
    app: my-app
    tier: backend
    env: production
    version: "1.0"

# Selectors — query objects by labels
# Equality-based
selector:
  matchLabels:
    app: my-app
    env: production

# Set-based
selector:
  matchExpressions:
    - {key: tier, operator: In, values: [backend, api]}
    - {key: env, operator: NotIn, values: [dev]}
    - {key: version, operator: Exists}

# kubectl commands:
# kubectl get pods -l app=my-app
# kubectl get pods -l 'tier in (backend,api),env!=dev'
# kubectl get pods -l app=my-app -l env=production

# Annotations — non-identifying metadata
metadata:
  annotations:
    description: "My app deployment"
    contact: "[email protected]"

Pod 스펙

Pod 스펙은 컨테이너, 이미지, 포트, 환경 변수(리터럴 또는 secret/configmap에서), 리소스(requests/limits), 프로브(readiness/liveness), 볼륨과 volumeMounts를 정의합니다. Pod는 가장 작은 배포 단위이지만 보통 Deployment를 통해 만들고 직접 만들지 않습니다.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: app
      image: my-app:1.0
      ports:
        - containerPort: 8080
          name: http
      env:
        - name: LOG_LEVEL
          value: info
        - name: SECRET_KEY
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: secret-key
      resources:
        requests: {cpu: 100m, memory: 128Mi}
        limits: {cpu: 500m, memory: 512Mi}
      readinessProbe:
        httpGet: {path: /health, port: 8080}
        initialDelaySeconds: 5
        periodSeconds: 10
      volumeMounts:
        - name: config
          mountPath: /etc/config
  volumes:
    - name: config
      configMap:
        name: app-config
  restartPolicy: Always

Deployment

Deployment는 ReplicaSet과 Pod를 관리합니다. spec.replicas는 원하는 개수를 설정합니다. strategy.type은 RollingUpdate(기본, maxSurge/maxUnavailable로 제어)나 Recreate입니다. pod 템플릿(spec.template)이 Pod 생성 방식을 정의합니다. kubectl rollout status/undo/history로 롤아웃을 관리하세요.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: app
          image: my-app:1.0.0
          ports:
            - containerPort: 8080
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits: {cpu: 500m, memory: 512Mi}
          readinessProbe:
            httpGet: {path: /ready, port: 8080}
  # Rollback / history
  # kubectl rollout status deployment/my-app
  # kubectl rollout undo deployment/my-app
  # kubectl rollout history deployment/my-app

Service

Service는 Pod를 네트워크 서비스로 노출합니다. type ClusterIP(기본)는 내부 전용이고 NodePort는 각 노드에서 노출하며 LoadBalancer는 클라우드 LB를 프로비저닝하고 ExternalName은 DNS CNAME입니다. selector가 트래픽을 일치하는 Pod로 라우팅합니다. ports는 서비스 포트를 컨테이너 targetPort(숫자 또는 이름)에 매핑합니다.

yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app
spec:
  type: ClusterIP      # ClusterIP (default), NodePort, LoadBalancer, ExternalName
  selector:
    app: my-app        # routes to pods with these labels
  ports:
    - name: http
      port: 80         # service port
      targetPort: 8080 # container port (or named port)
      protocol: TCP
    - name: https
      port: 443
      targetPort: 8443

# NodePort: exposes on each node's IP at a static port (30000-32767)
# LoadBalancer: provisions a cloud LB
# ExternalName: CNAME to an external service

# Service types:
# ClusterIP    - internal cluster IP (default)
# NodePort     - exposes on node port + ClusterIP
# LoadBalancer - cloud LB + NodePort + ClusterIP
# ExternalName - DNS CNAME (no proxying)

ConfigMap과 Secret

ConfigMap은 민감하지 않은 설정(문자열 또는 파일)을, Secret은 민감 데이터(data에는 base64, stringData에는 평문)를 담습니다. 둘 다 환경 변수(valueFrom)나 볼륨 마운트로 소비합니다. Secret은 기본적으로 암호화되지 않으므로 저장 시 암호화를 켜고 RBAC 접근을 제한하세요.

yaml
# ConfigMap — non-sensitive configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  log_level: info
  max_connections: "100"
  config.yaml: |
    server:
      host: 0.0.0.0
      port: 8080
---
# Secret — sensitive data (base64-encoded)
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
type: Opaque
data:
  # base64-encoded values
  api_key: c2VjcmV0LWtleS0xMjM=   # echo -n 'secret-key-123' | base64
  db_password: cGFzc3dvcmQ=
# Or use stringData for plain text (auto-encoded):
# stringData:
#   api_key: secret-key-123

# Consumed by pods:
# env:
#   - name: API_KEY
#     valueFrom:
#       secretKeyRef:
#         name: app-secrets
#         key: api_key
# volumes:
#   - name: config
#     configMap:
#       name: app-config
16

CI/CD 설정(GitHub Actions와 GitLab CI)

GitHub Actions 워크플로

GitHub Actions 워크플로는 .github/workflows/에 있습니다. on:은 트리거(push, PR, schedule, workflow_dispatch)입니다. jobs는 runs-on + steps를 담습니다. uses:는 액션을 참조하고 run:은 셸을 실행합니다. 표현식은 ${{ }} 문법을 쓰며 YAML 템플릿 리터럴 안에서는 \${{ }}로 이스케이프해야 합니다.

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm test
      - run: npm run build
        env:
          NODE_ENV: production

  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm run lint

# ${{ }} is GitHub Actions expression syntax
# MUST be escaped as ${{ }} in YAML template literals
# (here we use literal text, no escaping needed)

GitLab CI 파이프라인

GitLab CI는 .gitlab-ci.yml에 있습니다. stages는 파이프라인 순서를 정의합니다. jobs는 stage, image, script와 많은 옵션(only/except, rules, when, artifacts, environment)을 가집니다. 변수는 $VAR 문법을 쓰며 YAML 블록 스칼라에서는 이스케이프가 필요 없습니다. when: manual은 배포에 클릭이 필요합니다.

yaml
# .gitlab-ci.yml
stages:
  - test
  - build
  - deploy

variables:
  NODE_ENV: production
  IMAGE_TAG: $CI_COMMIT_SHORT_SHA

test:
  stage: test
  image: node:20
  script:
    - npm ci
    - npm test
  artifacts:
    reports:
      junit: test-results.xml
  coverage: '/Lines.*:\s(\d+\.\d+)\%/'

build:
  stage: build
  image: docker:24
  services:
    - docker:24-dind
  script:
    - docker build -t myapp:$IMAGE_TAG .
    - docker push myapp:$IMAGE_TAG
  only:
    - main

deploy:production:
  stage: deploy
  script:
    - ./deploy.sh
  environment:
    name: production
  only:
    - main
  when: manual   # require manual trigger

매트릭스 빌드

매트릭스 빌드는 다른 변수로 작업을 여러 번 실행합니다. GitHub Actions는 strategy.matrix에 include/exclude를 씁니다. GitLab은 parallel.matrix를 씁니다. fail-fast: false는 하나의 실패가 형제를 취소하지 않게 합니다. 크로스 플랫폼, 다중 버전 테스트에 유용합니다. ${{ }} 문법은 YAML 리터럴에서 이스케이프해야 합니다.

yaml
# GitHub Actions matrix
jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        node: [18, 20, 22]
        exclude:
          - os: windows-latest
            node: 18
        include:
          - os: ubuntu-latest
            node: 20
            experimental: true
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
      - run: npm ci
      - run: npm test

# GitLab CI matrix (parallel matrix):
# test:
#   image: node:${NODE_VERSION}
#   parallel:
#     matrix:
#       - NODE_VERSION: [18, 20, 22]
#         OS: [linux, macos]

재사용 워크플로와 include

두 시스템 모두 재사용을 지원합니다. GitHub Actions는 uses:로 호출하는 재사용 워크플로(workflow_call 트리거)를 씁니다. GitLab은 include(project, local, template, remote)를 씁니다. 재사용은 공유 CI 로직의 중복을 줄입니다. 워크플로를 합성 가능하고 감사 가능하게 유지하려면 입력/시크릿을 명시적으로 넘기세요.

yaml
# GitHub Actions: reusable workflow
# .github/workflows/reusable.yml
on:
  workflow_call:
    inputs:
      node-version:
        required: true
        type: string
    secrets:
      token:
        required: true
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm ci
        env:
          TOKEN: ${{ secrets.token }}

# Caller:
# jobs:
#   build:
#     uses: ./.github/workflows/reusable.yml
#     with:
#       node-version: '20'
#     secrets:
#       token: ${{ secrets.MY_TOKEN }}

# GitLab CI: include
# include:
#   - project: 'ci/templates'
#     file: '/node.yml'
#   - local: '/.gitlab/extra.yml'
#   - template: Jobs/SAST.gitlab-ci.yml

CI 설정의 앵커

YAML 앵커는 CI 설정의 중복을 줄입니다. GitLab CI는 이를 많이 씁니다. 숨은 작업(.template)을 &anchor로 정의한 뒤 <<: *anchor로 병합합니다. GitHub Actions는 앵커를 지원하지만 작업 간 사용은 권장하지 않습니다(재사용 워크플로 선호). 앵커는 설정을 DRY하게 하지만 추적이 어려우니 신중히 사용하세요.

yaml
# YAML anchors reduce duplication in CI configs
# GitLab CI commonly uses anchors

.default_template: &default_template
  image: node:20
  before_script:
    - npm ci
  cache:
    paths:
      - node_modules/

test:
  <<: *default_template
  script:
    - npm test

lint:
  <<: *default_template
  script:
    - npm run lint

build:
  <<: *default_template
  script:
    - npm run build
  artifacts:
    paths:
      - dist/

# GitHub Actions supports anchors too (since 2022):
# jobs:
#   base: &base
#     runs-on: ubuntu-latest
#     steps:
#       - uses: actions/checkout@v4
#   test:
#     uses: ./.github/workflows/reusable.yml
#   # Anchors across jobs are limited — prefer reusable workflows

환경과 시크릿

GitHub Actions 환경은 배포를 게이트(승인 요구, 브랜치 제한)하고 환경 범위 시크릿을 보관합니다. 시크릿은 ${{ secrets.NAME }}으로 참조합니다. GitLab은 UI에서 정의한 protected(브랜치 제한)와 masked(로그 숨김) 변수를 씁니다. 시크릿을 절대 로깅하지 마세요. 오류 출력에서 누출될 수 있습니다.

yaml
# GitHub Actions: environments & secrets
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment:
      name: production        # requires approval if configured
      url: https://app.example.com
    steps:
      - uses: actions/checkout@v4
      - name: Deploy
        run: ./deploy.sh
        env:
          DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
          API_TOKEN: ${{ secrets.API_TOKEN }}
          ENV: production

# Secret scopes:
# - Repository secrets: available to all workflows
# - Environment secrets: only when job uses that environment
# - Organization secrets: shared across repos

# GitLab CI: protected/masked variables
# variables:
#   # defined in UI: Settings > CI/CD > Variables
#   # - Protected: only on protected branches/tags
#   # - Masked: hidden in job logs
# deploy:
#   script:
#     - ./deploy.sh
#   environment:
#     name: production
#   only:
#     - main
17

보안 고려사항

역직렬화 위험

YAML 역직렬화는 !!python/object/apply 같은 태그가 임의 함수를 호출할 수 있어 위험합니다. PyYAML의 yaml.load()는 5.1 이전에 기본적으로 안전하지 않았습니다(신뢰할 수 없는 입력에서 코드 실행). 신뢰할 수 없는 입력에는 항상 yaml.safe_load()를 쓰세요. 객체 생성 태그를 거부합니다. 다른 언어도 비슷한 위험이 있습니다(SnakeYAML, Psych).

yaml
# YAML deserialization can be DANGEROUS.
# Some loaders let YAML instantiate arbitrary objects.

# DANGEROUS (PyYAML < 5.1, default was unsafe):
# data = yaml.load(untrusted_input)
# An attacker can craft YAML that runs arbitrary code:
# !!python/object/apply:os.system ["rm -rf /"]

# Other dangerous tags:
# !!python/object/apply:...     # call any Python function
# !!python/object/new:...       # instantiate any class
# !ruby/object:...               # Ruby object instantiation
# !java/object:...               # Java (SnakeYAML)

# Safe loaders reject these tags by default.
# Modern PyYAML (>= 5.1): yaml.load() requires a SafeLoader
# yaml.safe_load() is ALWAYS safe.

# Rule of thumb:
# - NEVER use yaml.load() on untrusted input
# - ALWAYS use yaml.safe_load() (or full_load on trusted files)
# - Or use a schema-validated loader

safe_load vs load

항상 safe_load(Python), safe_load(Ruby Psych), 기본 안전 스키마(js-yaml, Go yaml.v3)를 사용하세요. PyYAML 5.1+는 yaml.load()에 명시적 Loader가 필요합니다. full_load는 표준 태그를 허용하지만 임의 객체는 아니므로 신뢰할 수 있는 파일에만 사용하세요. 안전 로더는 모든 객체 생성 태그를 거부합니다.

yaml
# Python (PyYAML) — the classic safe/unsafe distinction

# SAFE: safe_load rejects all custom tags
import yaml
data = yaml.safe_load(untrusted_yaml)   # ALWAYS use this

# SAFE: load with SafeLoader (explicit)
data = yaml.load(untrusted_yaml, Loader=yaml.SafeLoader)

# FULL (trusted files only): full_load allows standard tags
# but not arbitrary python objects
data = yaml.full_load(trusted_yaml)

# UNSAFE: UnsafeLoader allows !!python/object — DANGEROUS
data = yaml.load(untrusted_yaml, Loader=yaml.UnsafeLoader)  # NEVER on untrusted

# PyYAML 5.1+ requires Loader argument for yaml.load()
# (raises error without it) — safety improvement.

# Other languages:
# JS (js-yaml): yaml.load(str) uses DEFAULT_SAFE_SCHEMA
# Go (yaml.v3): no object instantiation (safe by design)
# Ruby (Psych): Psych.safe_load is the safe variant
# Java (SnakeYAML): SafeConstructor for safe loading

로컬 태그 악용

커스텀 태그(!include, !env, !file, !exec, !template)는 !!python/object 없이도 악용될 수 있습니다. 파일을 읽는 !include는 경로 탐색으로 /etc/passwd나 .ssh/id_rsa를 읽도록 속일 수 있습니다. 모든 커스텀 생성자를 감사하세요. 경로를 허용 목록으로 검증하고 절대 경로와 ../를 거부하며 로더를 샌드박스하세요.

yaml
# Even non-builtin tags can be exploited if your loader
# registers constructors that have side effects.

# Example: a "harmless" custom tag
# yaml.add_constructor('!include', include_file)
#
# If !include reads files from disk, an attacker can
# craft YAML to read sensitive files:
# config: !include /etc/passwd
# or:
# config: !include /etc/shadow
# or:
# config: !include ../../../.ssh/id_rsa

# Mitigation:
# 1. Validate the included path against an allowlist
# 2. Restrict !include to a specific directory
# 3. Refuse absolute paths and ../ traversal
# 4. Run the loader in a sandbox

# Other "innocent" tags that can be exploited:
# !env VAR_NAME        -> leaks env vars
# !exec "command"      -> arbitrary command execution
# !file /path          -> file disclosure
# !template <% ... %>  -> code injection

# Audit every custom constructor for side effects.

Billion Laughs와 DoS

Billion Laughs 공격은 중첩 별칭으로 작은 문서를 기가바이트 메모리로 확장합니다(수준당 별칭 10개, 5수준 = 10^9 참조). 별칭 깊이 제한, 전체 크기 제한, 스트리밍 파서, 과도한 중첩 거부로 완화하세요. 깊은 중첩(스택 오버플로)과 거대한 평면 컬렉션도 주의하세요.

yaml
# "Billion Laughs" attack — exponential expansion via aliases
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d,*d]

# This 5-line document expands to ~10^9 string references
# consuming gigabytes of memory on parse.

# Mitigations:
# 1. Limit alias depth (some parsers do this)
# 2. Limit total parsed size / memory
# 3. Use a streaming parser for untrusted input
# 4. PyYAML has a limit but not all parsers do
# 5. Reject documents with excessive alias nesting

# Other DoS vectors:
# - Very deep nesting (parser stack overflow)
# - Huge flat sequences/mappings (memory)
# - Pathological number formats (regex backtracking)
# - Quadratic blowup via duplicate keys

# For untrusted input: set hard size + depth limits.

입력 검증

계층 검증: (1) 크기 제한, (2) safe_load로 위험 태그 거부, (3) 타입 검사(list가 아닌 dict 기대), (4) 스키마 검증(JSON Schema, Pydantic, Cue), (5) 도메인 검증(포트 범위 같은 비즈니스 규칙). 각 계층이 다른 공격을 잡습니다. 구조를 신뢰하지 말고 사용 전에 항상 검증하세요.

yaml
# Layered defense for untrusted YAML input:

# 1. Size limit (reject oversized input)
MAX_SIZE = 1024 * 1024  # 1 MB
if len(input_text) > MAX_SIZE:
    raise ValueError("input too large")

# 2. Safe parser (rejects dangerous tags)
import yaml
try:
    data = yaml.safe_load(input_text)
except yaml.YAMLError as e:
    raise ValueError(f"invalid YAML: {e}")

# 3. Type check (expect a mapping, not a list)
if not isinstance(data, dict):
    raise ValueError("expected a mapping at top level")

# 4. Schema validation (JSON Schema, Pydantic, etc.)
from pydantic import BaseModel, ValidationError
class Config(BaseModel):
    host: str
    port: int = 8080
try:
    config = Config(**data)
except ValidationError as e:
    raise ValueError(f"schema validation failed: {e}")

# 5. Domain validation (business rules)
if config.port < 1 or config.port > 65535:
    raise ValueError("port out of range")

라이브러리 권장

기본 안전 라이브러리를 선택하세요: PyYAML(safe_load), ruamel.yaml, js-yaml(기본 안전), Go yaml.v3, Psych.safe_load, SafeConstructor가 있는 SnakeYAML, serde_yaml. 명시적 안전 로더 없는 yaml.load는 피하세요. 보안 패치를 위해 최신 버전으로 고정하세요. 커스텀 생성자를 감사하고 라이브러리의 보안 문서를 읽으세요.

yaml
# Safe-by-default YAML libraries by language:

# Python:
#   - PyYAML >= 5.1 (yaml.safe_load)
#   - ruamel.yaml (safe by default, round-trip mode)
#   AVOID: yaml.load without explicit SafeLoader

# JavaScript/TypeScript:
#   - js-yaml (yaml.load uses DEFAULT_SAFE_SCHEMA)
#   AVOID: yaml.load with DEFAULT_FULL_SCHEMA on untrusted

# Go:
#   - gopkg.in/yaml.v3 (no object instantiation, safe)
#   AVOID: yaml.v2 has subtle differences, prefer v3

# Ruby:
#   - Psych (Psych.safe_load)
#   AVOID: YAML.load (uses unsafe loader in old Ruby)

# Java:
#   - SnakeYAML with SafeConstructor
#   AVOID: new Yaml() without SafeConstructor on untrusted
#   (SnakeYAML had CVEs from unsafe loading)

# Rust:
#   - serde_yaml (safe by design, no arbitrary types)

# General rule:
# - Read the library's security docs
# - Pin to a recent version (security patches)
# - Use safe_load / SafeConstructor / safe schema
# - Audit custom constructors for side effects
18

모범 사례

일관된 들여쓰기

2칸을 일관되게 사용하고(사실상 표준) 탭은 절대 쓰지 마세요. 편집기에서 YAML에 공백을 넣도록 설정하세요. 포매터(prettier, yamlfixer)와 린터(yamllint)로 일관성을 강제하세요. 일관되지 않은 들여쓰기는 가장 흔한 YAML 오류이고 파싱을 깨뜨립니다.

yaml
# Use 2 spaces for indentation (most common)
# NEVER use tabs (YAML forbids them)

# GOOD
server:
  host: localhost
  port: 8080
  routes:
    - path: /api
      handler: apiHandler
    - path: /web
      handler: webHandler

# BAD (inconsistent)
# server:
#    host: localhost
#   port: 8080      # wrong indent

# Configure your editor:
# VS Code: "[yaml]": {"editor.insertSpaces": true, "editor.tabSize": 2}
# Vim:     autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab
# Emacs:   (add-hook 'yaml-mode-hook
#           (lambda () (setq yaml-indent-offset 2)))

# Use a formatter:
# prettier (with yaml plugin) normalizes indentation
# yamllint checks it
# yamlfixer auto-fixes issues

인용 전략

숫자, 불리언, null, 날짜처럼 보이거나 콜론/쉼표/특수 문자가 있거나 표시자(- ? : * & ! | > ' " % @)로 시작하는 문자열은 따옴표로 감싸세요. 그 외에는 가독성을 위해 일반(따옴표 없음)을 선호하세요. 이스케이프 시퀀스(\n, \t)에는 큰따옴표를, 아포스트로피가 있는 리터럴 문자열에는 작은따옴표를 사용하세요.

yaml
# Quote strings when:
# 1. They look like another type (number, bool, null, date)
version: "1.0"        # string, not float
answer: "yes"         # string, not bool (1.1)
region: "no"          # string "no", not False (1.1)
date: "2024-01-01"    # string, not date
phone: "555-1234"     # string, not number

# 2. They contain special characters
url: "https://example.com:8080"   # colon
list: "a, b, c"                    # comma
expr: "value:with:colons"          # colons

# 3. They start with special indicators (-, ?, :, *, &, !, |, >, ', ", %, @, `)
flag: "-not-a-list"
key: "?not-a-complex-key"

# Don't quote otherwise — plain is more readable
name: Alice            # no quotes needed
path: /usr/local/bin   # no quotes needed

# Prefer double quotes for escapes (\n, \t)
# Prefer single quotes for literal strings with apostrophes
greeting: "Hello\nWorld"
possessive: 'Alice''s car'

탭과 기타 함정 피하기

흔한 함정을 피하세요: 탭(금지, 공백 사용), 따옴표 없는 yes/no/on/off(1.1 vs 1.2 모호성), 콜론이 있는 따옴표 없는 문자열, 뒤 공백, CRLF 줄 끝(LF 사용), BOM(BOM 없는 UTF-8로 저장), 매우 긴 줄(블록 스칼라로 감싸기). 린터가 대부분을 잡습니다.

yaml
# Pitfall 1: tabs for indentation (FORBIDDEN)
# Configure editor to use spaces

# Pitfall 2: yes/no/on/off as strings (1.1 vs 1.2)
# Always quote: "yes", "no", "on", "off"

# Pitfall 3: unquoted strings with colons
# bad:  url: http://x:8080
# good: url: "http://x:8080"

# Pitfall 4: trailing whitespace
# Some parsers are strict; linters always flag it
key: value   # <- no trailing spaces

# Pitfall 5: Windows line endings (CRLF)
# Use LF (\n) only — CRLF can cause subtle issues
# .gitattributes: *.yaml text eol=lf

# Pitfall 6: BOM at start of file
# Save as UTF-8 without BOM

# Pitfall 7: very long lines
# Wrap with block scalars or flow style
description: >
  This is a long description that wraps
  across multiple lines for readability.

# Pitfall 8: inconsistent key ordering
# Group related keys, be consistent

버전 고정과 스키마 문서

1.1 vs 1.2 차이가 중요하면 %YAML 1.2로 버전을 고정하세요. 스키마를 문서화하세요: 필수/선택 필드, 타입, 기본값, 범위를 주석, JSON Schema 파일, README에 남기세요. 코드에서 스키마 버전을 고정해 설정 검증을 재현 가능하게 하세요. 온보딩 마찰과 설정 오류를 줄입니다.

yaml
# Pin the YAML version if it matters
%YAML 1.2
---
key: value

# Document your schema expectations in comments:
# Required fields:
#   - host: string (hostname or IP)
#   - port: integer (1-65535)
# Optional fields:
#   - tls: boolean (default: false)
#   - cert: string (path, required if tls: true)

config:
  host: example.com
  port: 443
  tls: true
  cert: /etc/ssl/cert.pem

# Or use a JSON Schema file (config.schema.json)
# and reference it from your docs / CI:
# "Validated against schema v1.2; see config.schema.json"

# For libraries, document the schema in the README:
# ## Configuration
# The config.yaml file must contain:
# - host (str, required)
# - port (int, required, 1-65535)
# - tls (bool, optional, default: false)

# Pin schema versions in code:
# CONFIG_SCHEMA_VERSION = "1.2"
# validate(data, schema_v1_2)

CI에서 린팅

YAML 린팅을 CI(GitHub Actions, GitLab CI)와 pre-commit 훅에 연결하세요. 구문/스타일에는 yamllint, 서식에는 prettier를 사용하세요. 편집기 통합(VS Code YAML 확장, yaml-language-server)이 인라인 린팅과 스키마 검증을 제공합니다. YAML 오류를 CI에서 잡는 것이 운영 환경보다 훨씬 저렴합니다.

yaml
# .github/workflows/lint.yml
name: Lint YAML
on: [push, pull_request]
jobs:
  yamllint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install yamllint
        run: pip install yamllint
      - name: Lint
        run: yamllint -s .

# GitLab CI:
# yamllint:
#   image: python:3.12
#   script:
#     - pip install yamllint
#     - yamllint -s .

# Pre-commit hook (.pre-commit-config.yaml):
# repos:
#   - repo: https://github.com/adrienverge/yamllint
#     rev: v1.35.1
#     hooks:
#       - id: yamllint
#         args: [-s, --config-file, .yamllint.yml]
#   - repo: https://github.com/pre-commit/mirrors-prettier
#     rev: v3.1.0
#     hooks:
#       - id: prettier
#         types: [yaml]

# Editor integration:
# VS Code: install "YAML" extension (redhat)
#   + "yamllint" for inline linting
#   + schema validation via yaml-language-server

구조와 가독성

관련 키를 주석 헤더로 묶으세요. 중첩은 얕게 유지하세요(최대 3-4수준). 깊게 중첩된 YAML은 읽기 어렵습니다. 진짜 재사용되는 값에는 앵커를 사용하세요. 여러 줄 문자열에는 블록 스칼라를 사용하세요. 줄은 120자 미만으로 유지하세요. 사람이 YAML을 편집하므로 가독성이 중요합니다.

yaml
# Group related keys; use comments to delineate sections
server:
  # Networking
  host: 0.0.0.0
  port: 8080
  tls:
    enabled: true
    cert: /etc/ssl/cert.pem

  # Limits
  timeout: 30
  max_connections: 100
  retries: 3

# Keep nesting shallow (3-4 levels max)
# Deeply nested YAML is hard to read and edit.

# If a value is reused, use an anchor:
defaults: &defaults
  timeout: 30
  retries: 3

prod:
  <<: *defaults
  env: production

staging:
  <<: *defaults
  env: staging

# Use block scalars for multi-line values
script: |
  #!/bin/bash
  set -e
  echo "deploying"

# Keep lines under 120 chars; wrap with block scalars or
# multi-line flow style.
19

고급 기능

복잡한 매핑 키

? 표시자는 복잡한 키(키로 쓰이는 매핑이나 시퀀스)를 표시합니다. 조회 테이블(예: 지역+인스턴스별 가격)에 유용합니다. 주의: 많은 직렬화기가 복잡한 키를 보존하지 않고 출력 시 문자열화할 수 있습니다. 대부분 설정 파일은 단순성과 도구 호환성을 위해 일반 문자열 키를 고수합니다.

yaml
# Use ? to mark a complex (non-scalar) key
? apple
: red fruit

? orange
: orange fruit

# A mapping as a key
? host: localhost
  port: 8080
: connection_string

# A sequence as a key
? [us-east-1, t2.micro]
: 0.0116
? [us-east-1, t2.small]
: 0.023
? [us-west-2, t2.micro]
: 0.0125

# Useful for lookup tables
pricing:
  ? [production, large]
  : 100
  ? [production, small]
  : 50
  ? [development, large]
  : 20

# In flow style:
{[a, b]: value, {x: 1}: other}

# Caveat: many serializers don't preserve complex keys
# and may convert them to strings on output.

집합(!!set)

YAML 집합(!!set)은 키가 요소이고 값이 null인 매핑입니다. 일부 파서는 네이티브 Set 타입으로 매핑합니다. 고유 컬렉션(역할, 권한)을 선언할 때 사용하세요. 주의: JSON에는 Set 타입이 없어 JSON 변환 시 null 값을 가진 객체가 됩니다. 모든 직렬화기가 !!set 태그를 보존하지는 않습니다.

yaml
# A set is a mapping with null values
# Use the !!set tag for clarity
permissions: !!set
  ? read
  ? write
  ? execute

# Equivalent to:
permissions:
  read: null
  write: null
  execute: null

# Or in flow style:
flags: !!set { red, green, blue }

# Parsers may map this to a native Set type:
# Python: set() (PyYAML with !!set constructor)
# Ruby: Set (Psych)
# JavaScript: depends on library

# Use case: declare a unique collection
roles: !!set
  ? admin
  ? editor
  ? viewer

# Caveat: JSON has no Set type, so JSON conversion
# usually produces an object with null values.

순서 있는 매핑(!!omap)

!!omap(순서 있는 매핑)은 삽입 순서를 보존하는 단일 키 매핑의 시퀀스입니다. 타임라인, 순서 있는 선호도, 순서가 의미상 중요한 곳에 유용합니다. 최신 파서는 일반 매핑 순서도 보존하지만(Python dict 3.7+, Ruby Hash) Go 맵은 무작위이므로 !!omap이 순서를 명시합니다.

yaml
# An ordered mapping preserves key order
# Use !!omap tag
timeline: !!omap
  - 2024-01-01: event A
  - 2024-02-01: event B
  - 2024-03-01: event C

# Equivalent representation as a list of single-key mappings:
# timeline:
#   - 2024-01-01: event A
#   - 2024-02-01: event B
#   - 2024-03-01: event C

# Parsers may map this to:
# Python: list of tuples, or OrderedDict
# Ruby: Array of one-key hashes (or OrderedDict)
# Go: ordered map (with custom type)

# Use case: ordered key-value pairs where order matters
# - event timelines
# - ordered preferences
# - step-by-step configurations

# Caveat: regular YAML mappings DO preserve order in
# most modern parsers (Python dict 3.7+, Ruby Hash,
# Go map iteration is random though). !!omap makes the
# intent explicit and works even where maps are unordered.

바이너리 데이터(!!binary)

!!binary는 바이너리 데이터를 YAML에 base64로 인코딩합니다. 파서는 네이티브 바이트(Python bytes, Ruby ASCII-8BIT 문자열)로 디코드합니다. 작은 이미지나 아이콘을 직접 임베드할 때 유용합니다. 큰 바이너리에는 경로나 URL 참조를 선호하세요. 여러 줄 base64는 폴디드(>)나 리터럴(|) 블록 스칼라와 동작합니다.

yaml
# Encode binary data as base64 with !!binary tag
image: !!binary "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9
  awAAAABJRU5ErkJggg=="

# Multi-line base64 (folded or literal works)
data: !!binary |
  iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42m
  k+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==

# Parsers decode to bytes:
# Python: bytes object
# Ruby: ASCII-8BIT string
# JavaScript: depends on library (often base64 string)

# Use case: embed small images, icons, or other binary
# directly in YAML config

# For larger binary data, prefer:
# - Reference by path:  image: /path/to/image.png
# - Reference by URL:   image: https://example.com/img.png
# - Store separately and link

# Verify with:
# python -c 'import yaml; d=yaml.safe_load(open("f.yaml")); print(len(d["image"]))'

커스텀 생성자

커스텀 생성자를 등록해 태그(!money)를 네이티브 객체에 매핑하세요. SafeLoader 범위의 로더와 함께 add_constructor를 사용하세요. 생성자는 로더와 노드를 받고 construct_scalar/mapping/sequence로 노드 값을 읽습니다. 생성자의 부수 효과(파일 읽기, 서브프로세스 호출)를 항상 감사하세요. 신뢰할 수 없는 입력으로 악용될 수 있습니다.

yaml
# PyYAML: register a constructor for a custom tag
import yaml

class Money:
    def __init__(self, currency, amount):
        self.currency = currency
        self.amount = amount
    def __repr__(self):
        return f"Money({self.currency} {self.amount})"

def money_constructor(loader, node):
    value = loader.construct_scalar(node)  # "USD 19.99"
    currency, amount = value.split()
    return Money(currency, float(amount))

# Register the constructor (use SafeLoader scope)
yaml.add_constructor('!money', money_constructor, Loader=yaml.SafeLoader)

# Now this YAML parses to a Money object:
# price: !money "USD 19.99"
config = yaml.safe_load("price: !money \"USD 19.99\"")
print(config['price'])  # Money(USD 19.99)

# Multi-argument constructors use construct_mapping or
# construct_sequence depending on the node kind.

# SECURITY: audit every constructor for side effects.
# A constructor that calls open(), os.system(), or
# subprocess can be exploited via untrusted input.

YAML 1.2 기능과 미래

YAML 1.2는 JSON을 엄격한 부분 집합으로 만들고 불리언을 true/false로 제한하며 8진수에 0o를 채택했습니다. 병합 키 <<는 코어 명세에서 제거되었지만 여전히 널리 지원됩니다. YAML 1.2.2(2021)는 명세를 명확히 했고 1.3이 개발 중입니다. 버전을 고정하고 모호한 문자열을 인용하며 복잡한 설정에는 Cue/Dhall/Jsonnet을 고려해 미래에 대비하세요.

yaml
# YAML 1.2 (2009, current spec) key changes from 1.1:
# - JSON is a strict subset
# - Booleans: only true/false (not yes/no/on/off)
# - Octal: 0o prefix (not leading 0)
# - Removed sexagesimal numbers
# - Removed merge key << from core spec (still widely supported)

# YAML 1.3 (in development) aims to:
# - Clarify ambiguous parts of 1.2
# - Standardize error reporting
# - Improve interoperability between parsers
# - Possibly restore some 1.1 features as optional

# YAML 1.2.2 (2021 update, spec revision):
# - Clarified type resolution
# - Better-defined core schema
# - Improved examples
# - No breaking changes

# Recommended practices for future-proofing:
# 1. Pin %YAML 1.2 in critical files
# 2. Quote ambiguous strings (yes/no, leading-zero numbers)
# 3. Avoid relying on << merge key for new formats
#    (or document that you depend on it)
# 4. Use JSON-compatible subset when interop matters
# 5. Watch for YAML 1.3 adoption in your parser

# Some tools (Cue, Dhall, Jsonnet) extend/replace YAML
# for complex configuration — consider them for new
# projects with advanced needs.

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.