Plain unquoted string — most common
name: John Doe
Single-quoted: no variable or escape processing
path: '/usr/bin/node'
Double-quoted: supports escape sequences (\n, \t, etc.)
message: "Hello\nWorld"
Whole number (base 10)
port: 8080
Floating point number
threshold: 0.95
Boolean value — use only true/false (YAML 1.2)
debug: false
Null / absence of value
response: null
ISO 8601 date format
created: 2024-01-15T10:30:00Z
Single-line comment. No multi-line comment syntax.
# This is a comment key: value # inline comment
Force value to be treated as a specific type
port: !!str 8080 # string '8080' not int
Key-value pairs — indented block style
app: name: myapp port: 3000
Inline map — equivalent to block style
env: {NODE_ENV: prod, PORT: 8080}List of items — block style with dash+space
fruits: - apple - banana - cherry
Inline list — equivalent to block style
ports: [80, 443, 8080]
List where each item is a map
users:
- name: Alice
role: admin
- name: Bob
role: userArbitrarily deep nesting
database:
primary:
host: db1.example.com
port: 5432Merge the keys of a referenced mapping into current map
defaults: &defaults color: blue button: <<: *defaults text: Submit
Preserves newlines exactly as written
script: | #!/bin/bash echo "hello" exit 0
Newlines folded into spaces (great for long descriptions)
description: > This is a very long description that will be joined into one line.
Literal block, strip all trailing newlines
prompt: |- Enter value:
Literal block, keep all trailing newlines
template: |+ line1
Folded block, strip trailing newlines
message: >- This folds into one line no trailing newline
Assigns an anchor (label) to the current node
base: &base image: node:18 restart: always
References (copies) an anchored node
service1: <<: *base name: api service2: <<: *base name: worker
Anchor a scalar value to reuse it
read_timeout: &rto 30 write_timeout: *rto connect_timeout: *rto
Anchor a list
primary_colors: &colors - red - blue text_colors: *colors
Explicitly declare YAML version (optional, rarely needed)
%YAML 1.2 --- name: myapp
Marks the start of a YAML document. Required if using directives.
--- kind: Deployment --- kind: Service
Marks the end of a YAML document. Optional but useful.
--- debug: true ...
Multiple YAML docs in one file (stream)
Used in Kubernetes multi-resource files
Base64-encoded binary data
icon: !!binary | iVBORw0KGgo=
Indentation MUST use spaces only — never tabs
# WRONG: parent: \tchild: value # RIGHT: parent: child: value
Values containing ': ' (colon+space) must be quoted
# WRONG: url: http://example.com # RIGHT: url: "http://example.com"
1.0 parses as float! Quote or tag it to keep as string
version: '1.0' # string version: 1.0 # float
YAML 1.1 parses yes/no/on/off as booleans — quote to use strings
# YAML 1.1 (PyYAML): on: true # 'on' is boolean true! # Safe: always quote on: 'on'
Trailing spaces in keys are included in the key string
"key " (with space) != "key" — trim carefully
Duplicate keys — behavior is parser-specific (usually last wins). Treat as error.
Use a YAML linter to detect duplicate keys
| 기능 | YAML | JSON |
|---|---|---|
| 주석 | Yes: # comment | 지원되지 않음 |
| 따옴표 필요 | 문자열의 경우 선택 사항 | 문자열의 경우 필수 |
| Anchors/aliases | Yes: &anchor / *alias | 지원되지 않음 |
| 다중 라인 문자열 | Yes: | and > blocks | Escaped \n only |
| 들여쓰기에 탭 | 공백만 | 모두 가능 |
| JSON의 상위 집합 | 모든 JSON은 유효한 YAML | - |
| 사람이 읽기 쉬움 | 매우 높음 | 중간 |
| 파서 가용성 | 높음 | 매우 높음 |
중요: 많은 YAML 파서가 여전히 기본적으로 YAML 1.1을 사용합니다 (Python의 PyYAML, 일부 버전의 Ruby의 Psych).
YAML에는 두 가지 멀티라인 스타일이 있습니다:
리터럴 블록 (|) — 줄 바꿈 유지:
description: |
이것은 첫 번째 줄입니다.
이것은 두 번째 줄입니다.
이것은 네 번째 줄입니다 (빈 줄 이후).
접힌 블록 (>) — 줄을 공백으로 연결:
description: >
이것은 하나의 줄로
접히는 긴 문단
입니다.
후행 개행을 제거하려면 -를 추가하고 (|-, >-), 유지하려면 +를 사용하세요 (|+, >+).
단일 YAML 파일이 ---로 구분된 여러 문서를 포함할 수 있습니다:
---
# 문서 1: 설정
apiVersion: v1
kind: ConfigMap
---
# 문서 2: 서비스
apiVersion: v1
kind: Service
이것은 Kubernetes 매니페스트에서 일반적으로 사용됩니다.
2칸이 가장 일반적인 관례로, Kubernetes, Docker Compose, GitHub Actions, 대부분의 DevOps 도구에서 사용됩니다. 일부 프로젝트는 4칸을 사용합니다. 핵심 규칙은 파일 내 일관성입니다 — 들여쓰기 레벨을 절대 혼합하지 마세요.
네, YAML은 #으로 한 줄 주석을 지원합니다. 여러 줄 주석 구문은 없습니다. 주석은 파싱 중에 제거되며 로드된 데이터 구조에서 사용할 수 없습니다.
YAML은 JSON의 상위 집합입니다 — 유효한 JSON은 모두 유효한 YAML입니다. YAML은 주석, 다중 라인 문자열, 앵커/에일리어스를 지원하여 사람이 읽기 쉽도록 설계되었습니다. JSON은 더 엄격하고, 파싱이 빠르며, 보편적으로 지원됩니다. 구성 파일에는 YAML을, API 및 데이터 교환에는 JSON을 사용하세요.
YAML 1.1(PyYAML을 포함한 많은 파서에서 사용)에서는 'on', 'off', 'yes', 'no'가 유효한 불리언 값입니다. 이로 인해 일반 문자열로 사용할 때(예: Ansible에서) 버그가 발생할 수 있습니다. YAML 1.2에서 이 문제가 해결되어 'true'와 'false'만 불리언입니다. 해결책: 문자열로 사용하려면 항상 이 값들을 따옴표로 묶으세요('yes', 'no').
리터럴 블록 스칼라(|)를 사용하여 줄바꿈을 보존하세요: 블록의 각 줄이 문자열의 실제 줄바꿈이 됩니다. 접힌 블록 스칼라(>)를 사용하여 줄바꿈을 공백으로 변환하세요: 긴 단락에 좋습니다. 둘 다 선택적 chomping 표시기를 지원합니다(- 는 후행 줄바꿈 제거, + 는 모두 유지).
YAML은 들여쓰기에 공백을 사용합니다 — 탭은 절대 사용하지 않습니다. 모든 형제 키는 같은 들여쓰기 수준이어야 합니다. 탭과 공백을 혼용하면 항상 오류가 발생합니다. 일반적인 해결책: 편집기의 '탭을 공백으로 바꾸기' 설정 활성화, linter(yamllint) 사용, 파일 전체에서 일관된 들여쓰기 너비(공백 2 또는 4개) 유지.