はじめに
基本の構造
ネストのためインデント(スペースで、タブでなく)を使うのが、YAML です。マッピングが key: value を使い、シーケンスが - item を使います。インラインの構文が、リストに [] を、マップに {} を使います。コメントが # を使います。
# YAML uses indentation for structure
# Comments start with #
# Key-value pairs (mappings)
name: Alice
age: 30
# Nested mappings (use consistent indentation)
person:
name: Bob
age: 25
address:
city: NYC
zip: 10001
# Sequences (lists)
hobbies:
- reading
- coding
- music
# Inline syntax
numbers: [1, 2, 3]
coords: {x: 10, y: 20}コメント
# で始まり、空白か行の開始が先行されなければならないのが、コメントです。ブロックスカラー(| と >)の内側では、# がコメントでなくリテラルのコンテンツです。マルチラインのコメントの構文はなく — 各行が自身の # を必要とします。
# Full-line comment
key: value # Inline comment (whitespace before # required)
# Comments can appear anywhere
# - before documents
# - inside sequences
list:
- a # first item
- b # second item
# Block scalar headers DO accept comments
text: | # literal block
line one
# But the content of block scalars is literal,
# so # inside is NOT a comment:
literal: |
# this is part of the string, not a commentインデントの規則
インデントのためのタブを YAML が 厳格に禁止します — スペースだけが許されます。レベル内で一貫していなければならないのがインデントですが、固定数である必要はありません。シーケンスの - が、インデントの一部です。タブとスペースの混合が、パーサーのエラーを投げます。
# Use SPACES only — tabs are forbidden for indentation
# 2 spaces is the most common convention
mapping:
nested:
deeply_nested: value
# Sequences can be indented at the same level as the key
items:
- one
- two
# Or indented further (both are valid)
items2:
- one
- two
# WRONG: tab characters cause parser errors
# bad: value (tab before value)
# Hyphen counts as indentation start
- item1
- item2文書の開始と終了
YAML 文書の開始を印付けるのが、--- で、終了を印付けるのが、... です。(--- で区切られた複数の文書である)文書ストリームを 1 つのファイルが含められます。単一文書の設定ファイルのためには、先頭の --- がオプションですが、パーサーへのヒントとして推奨されます。
# --- 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よくある落とし穴
マッピングのセパレータであるためには、コロンの後にスペースが必要です。yes/no/on/off(1.1 ではブール、1.2 では文字列)と 8 進のリテラルで異なるのが、YAML 1.1 対 1.2 です。null であるのが空の値で、空の文字列と区別されます。多くのパーサー(PyYAML)が、まだ 1.1 の規則に従います。
# Colon needs a space after it
key:value # WRONG: parsed as a single string "key:value"
key: value # correct
# Yes/No/On/Off are NOT booleans in YAML 1.2
# (they WERE in YAML 1.1 — common gotcha)
answer: yes # YAML 1.1: true; YAML 1.2: "yes" string
# Numbers with leading zeros
version: 010 # YAML 1.1: octal 8; YAML 1.2: string "010"
# Unquoted strings with special chars
url: example.com/path # OK
url: example.com:8080 # WRONG: parsed as mapping with key example.com
# Empty values
empty: # null
empty2: ~ # explicit null
empty3: "" # empty string (different from null)YAML 対 JSON
JSON が厳密なサブセットになるよう設計されたのが、YAML 1.2 です — 任意の JSON ファイルが有 効な YAML です。YAML が加えるもの:コメント、ブロック構造、アンカー、マルチラインの文字列、タグです。すべてのキーと文字列の値を引用することを要求するのが、JSON で、YAML が素のスカラーのために緩めるものです。
# JSON is a strict subset of YAML 1.2
# Every valid JSON document is valid YAML
# JSON:
{"name": "Alice", "age": 30, "hobbies": ["a", "b"]}
# Equivalent YAML:
name: Alice
age: 30
hobbies:
- a
- b
# YAML adds: comments, multi-line strings, anchors,
# relaxed quoting, tags, multiple documents
# YAML removes: mandatory quotes around strings,
# commas, braces (in block style)
# YAML is a superset of JSON — not the other way.
# Comments and anchors are not valid JSON.スカラー(文字列、数値、ブール、Null)
素と引用された文字列
数値、ブール、null、日付のように見えない限り、引用を必要としないのが、素の文字列です。「''」の二重化により「'」だけをエスケープするのが、単一引用符で、他のエスケープがありません。完全なエスケープシーケンス(\n、\t、\uXXXX)をサポートするのが、二重引用符です。文字列の型を強制するのが、引用です。
# Plain strings (no quotes) — most common
name: Alice
path: /usr/local/bin
url: https://example.com
# Single-quoted — escape ' by doubling
msg: 'it''s fine'
# Double-quoted — supports escapes
greeting: "Hello\nWorld"
unicode: "\u03B1" # Greek alpha
tab: "col1\tcol2"
# Multi-word plain strings are fine
description: This is a plain string with spaces
# Strings that look like other types must be quoted
version: "1.0" # string, not float
notBool: "true" # string, not boolean
notNull: "null" # string, not null
date: "2024-01-01" # string, not date数値
8 進に 0o を使うのが、YAML 1.2 です(YAML 1.1 は先頭の素の 0 を使いました)。読みやすさのための数値 内のアンダースコアが許されます。特殊な float のリテラルであるのが、.inf と .nan です。文字列であるべきだが数値的に見える値(バージョン、電話番号、ID)は、必ず引用しましょう。
# Integers
int: 42
negative: -17
positive: +100
underscored: 1_000_000 # readable grouping (YAML 1.2)
# Octal & hex (YAML 1.2 prefixes)
octal: 0o17 # = 15 decimal
hex: 0xFF # = 255 decimal
binary: 0b1010 # = 10 decimal
# Floats
pi: 3.14159
exp: 1.0e+3 # 1000.0
neg_exp: -2.5e-4
# Special float values (IEEE 754)
infinity: .inf
neg_infinity: -.inf
not_a_number: .nan
# To force a string that looks numeric:
version: "1.0"
phone: "555-1234"ブール
ブールを true/false(と True/False、TRUE/FALSE)だけに狭めたのが、YAML 1.2 です。yes/no/on/off/y/n をブールとして扱うのが、(PyYAML が使う)YAML 1.1 です — 有名なバグの源です(例:ノルウェーの「no」→ false)。文字通りの意味なら、これらの文字列を必ず引用しましょう。
# YAML 1.2 — only these are booleans:
enabled: true
disabled: false
# YAML 1.1 ALSO accepts (common gotcha):
# yes, no, on, off, y, n, Y, N
# These are strings in 1.2 but booleans in 1.1
# To force a string:
answer: "yes" # always a string
option: "on"
flag: "y"
# PyYAML (1.1 rules) parses these as booleans:
# yes -> True, no -> False, on -> True, off -> False
# This breaks "no" as an answer or country code!
# Safe practice: quote if you mean the literal string
country: "no" # Norway country code, not FalseNull の値
null として、null、Null、NULL、~、空の値を受け付けるのが、YAML です。空の値(コロンの後に何もないキー)が null であり、空の文字列 "" と区別されます。ホスト言語の null 値(None、null、nil)へ YAML の null をマッピングするのが、パーサーです。
# 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 で、時間があると datetime になります。文字列として保つには、値を引用しましょう。タイムゾーンの指示子(Z、+08:00)がサポートされます。
# Date (ISO 8601)
date: 2024-01-15
# Datetime (ISO 8601)
datetime: 2024-01-15T14:30:00
datetime_tz: 2024-01-15T14:30:00Z
datetime_offset: 2024-01-15T14:30:00+08:00
datetime_space: 2024-01-15 14:30:00
# To force string (not a date):
not_a_date: "2024-01-15"
not_a_date2: '2024-01-15'
# Parsers typically return datetime objects
# Python: datetime.date / datetime.datetime
# JavaScript: Date (depending on library)型の推論
スキーマ経由で、引用されていないスカラーを解決するのが、YAML の型システムです。すべてを文字列として扱うのが、Failsafe スキーマで、int、float、bool、null、日付を推論するのが、JSON と Core のスキーマです。必要なとき解決を上書きするには、引用か明示的なタグ(!!str、!!int)を使いましょう。
# YAML infers types from unquoted scalars
str: hello # string
int: 42 # integer
float: 3.14 # float
bool: true # boolean
null_val: null # null
date: 2024-01-01 # date
list: [1, 2, 3] # sequence
# Force string type with quotes
str_version: "42"
str_date: "2024-01-01"
str_bool: "true"
# Or with the !!str tag
forced: !!str 42 # string "42"
forced_int: !!int "42" # integer 42
# Resolution depends on the schema
# Failsafe: everything is a string
# JSON/Core: numbers, bools, null inferredマッピング
単純なマッピング
キーが典型的に文字列である、key: value のペアであるのが、マッピングです。任意のスカラー(数値、ブール、null さえ)であり得るのが、キーです。重複キーは推奨されず、挙動がパーサーにより異なります(しばしば最後のものが勝ちます)。偶発的な重複を捉えるには、リンターを使いましょう。
# A mapping is a set of key: value pairs
name: Alice
age: 30
email: [email protected]
# Keys can be any scalar type (string, number, bool)
"string key": value
123: numeric key
true: boolean key
# Duplicate keys are technically discouraged
# but some parsers allow them (last wins)
key: first
key: second # overrides "first" in many parsers
# Values can be any type
mixed:
string: text
number: 42
list: [1, 2, 3]
nested:
deep: valueネストしたマッピング
子のキーをインデントすることで作られるのが、ネストしたマッピングです。レベル内で一貫していなければならないのが、インデントです。固定のインデントサイズはありませんが、事実上の標準が 2 スペースです。読みやすさが、深いネストで減ります — 非常に深い構造の平坦化を考えましょう。
# Nest mappings with consistent indentation
server:
host: localhost
port: 8080
ssl:
enabled: true
cert: /etc/ssl/cert.pem
key: /etc/ssl/key.pem
database:
primary:
host: db1.example.com
port: 5432
replica:
host: db2.example.com
port: 5432
# Indentation level is up to you — just be consistent
# 2 spaces is the most common conventionシーケンスのマッピング
マッピングとシーケンスが、自由に合成します。よくあるパターンであるのが、(レコードのリストである)マッピングのシーケンスで、各 - がアイテムを開始し、整列されたキーがそのアイテムに属します。- の後の最初のキーと、後続のキーのインデントが整列しなければなりません。
# Values in a mapping can be sequences
servers:
- web1.example.com
- web2.example.com
- web3.example.com
# Sequence of mappings (very common)
users:
- name: Alice
age: 30
- name: Bob
age: 25
# Each - starts a new item; aligned keys form one mapping
services:
- name: api
port: 8080
env:
- dev
- prod
- name: web
port: 3000
# Mixed: mapping containing sequence containing mapping
config:
endpoints:
- path: /health
method: GET
- path: /users
method: POST複雑なキー
? のキー指示子を使い、任意のスカラーかコレクションをキーとして許すのが、YAML です。設定ファイルではまれですが、(例:region+instance による価格の)ルックアップテーブルに有用です。読みにくいのが、複雑なキーです — ほとんどの設定ファイルが、素の文字列のキーに留まります。
# 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 に似た)フロースタイルです。1 行の短くコンパクトなデータに有用です。JSON と違い、YAML は末尾のカンマを許しません。フローとブロックのスタイルを自由に混ぜましょう。しかし、設定ファイルでの読みやすさのためには、ブロックを優先しましょう。
# Flow style mapping (like JSON)
point: {x: 10, y: 20}
config: {host: localhost, port: 8080}
# Nested flow mappings
nested: {a: {b: {c: value}}}
# Mixed flow and block
block_key:
flow_value: {x: 1, y: 2}
another: value
# Flow with sequences
mixed: {nums: [1, 2, 3], name: test}
# Quoting still works in flow style
quoted: {"key with space": "value", count: 3}
# Trailing comma is NOT allowed in YAML flow
bad: {a: 1, b: 2,} # parse errorキーの順序とスタイル
スペックでマッピングの順序を YAML 自体が保ちますが、(ほとんどのモダンな dict は保ちますが)ホスト言語のオブジェクトは保たないかも知れません。設定の読みやすさのためには:関連するキーをグループ化し、一貫した命名(snake_case か camelCase)を使い、セクションを区切るコメントを加えましょう。
# YAML mappings are ORDERED (unlike JSON spec, though
# most JSON parsers preserve insertion order too)
# But language objects may not preserve order:
# Python dict (3.7+): preserves order
# Ruby Hash: preserves order
# JSON object: technically unordered
# Consistent key style improves readability
config:
server:
host: localhost # snake_case
port: 8080
max_connections: 100
database:
host: db.example.com
port: 5432
connection_pool: 10
# Group related keys together
# Use comments to delineate sections
app:
# networking
host: 0.0.0.0
port: 3000
# limits
timeout: 30
retries: 3シーケンス
ブロックシーケンス
各アイテムの前の - (ハイフン + スペース)を使うのが、ブロックシーケンスです。任意のタイプであり得るのが、アイテムです:スカラー、マッピング、ネストしたシーケンスです。- がインデントの一部として数えられるため、マッピングのアイテムの後続のキーが、ハイフンの後の最初のキーと整列します。
# A sequence (list) uses - followed by space
fruits:
- apple
- banana
- cherry
# Sequence as top-level document
- item1
- item2
- item3
# Empty sequence
empty: []
or_with_marker: []
# Sequence with mixed types
mixed:
- string
- 42
- true
- null
- key: value # a mapping as an itemネストしたシーケンス
さらに - のレベルをインデントすることで形成されるのが、ネストしたシーケンスです。2 レベルを超えると読みにくくなります — 内側のシーケンスには、フロースタイルに切り替えましょう。純粋なネストしたシーケンスより読みやすいのが、(子を持つマッピングのシーケンスである)ツリー構造です。
# Sequence of sequences
matrix:
- - 1
- 2
- 3
- - 4
- 5
- 6
# More readable with flow style for inner
matrix2:
- [1, 2, 3]
- [4, 5, 6]
# Deeply nested
tree:
- name: root
children:
- name: child1
children:
- name: grandchild1
- name: child2
# 3D: sequence of sequence of sequence
cube:
- - [1, 2]
- [3, 4]
- - [5, 6]
- [7, 8]]マッピングのシーケンス
最もよくある YAML のパターンであるのが(レコードのリスト)、マッピングのシーケンスです。新しいアイテムを各 - が開始し、同じインデントの後続のキーがそのアイテムに属します。読みやすさのために、- の後にキーを整列させましょう。空のマッピングのアイテムが、{} と書かれます。
# Most common pattern: list of records
users:
- name: Alice
email: [email protected]
roles:
- admin
- user
- name: Bob
email: [email protected]
roles:
- user
# Each - starts a new mapping; aligned keys belong
# to that item. Indent the first key after - by 2 spaces.
servers:
- host: web1.example.com
port: 8080
healthy: true
- host: web2.example.com
port: 8080
healthy: false
# Empty mapping item
list:
- {}
- name: realインライン(フロー)シーケンス
[] を使い、ブロックシーケンスと等価であるのが、フローシーケンスです。1 行の短いリストに有用です。読みやすさのため 、フローシーケンスが複数行にまたがれます。JSON と違い、YAML が末尾のカンマを禁止します。ブロックのマッピングとフローシーケンスを自由に混ぜましょう。
# Flow sequence (JSON-like)
numbers: [1, 2, 3]
names: [Alice, Bob, Charlie]
# Nested flow sequences
matrix: [[1, 2], [3, 4]]
# Flow sequence of flow mappings
points: [{x: 1, y: 2}, {x: 3, y: 4}]
# Mixed: block mapping with flow sequence value
config:
ports: [80, 443, 8080]
hosts: [web1, web2, web3]
# Spread across multiple lines (still flow style)
long_list: [
item1,
item2,
item3
]
# NO trailing comma allowed
bad: [1, 2, 3,] # error混合と異種のコンテンツ
シーケンスとマッピングで、完全に異種のコンテンツを YAML が許します — 任意のアイテムが任意のタイプです。この柔軟性は強力ですが、アプリケーションが構造を検証しなければなりません。厳密な検証のためには、(JSON Schema、Cue などの)スキーマを使いましょう。
# Sequences can mix types freely
mixed:
- string
- 42
- true
- null
- [1, 2, 3] # nested sequence
- key: value # mapping
another: value2
- - nested
- sequence
# Heterogeneous mapping values
config:
string_val: text
int_val: 42
list_val: [a, b, c]
map_val: {x: 1, y: 2}
null_val: null
bool_val: true
# YAML has no schema enforcing uniformity —
# the application must validate structureシーケンスのインデントのパターン
キーの下のシーケンスが、インデントでき(パターン 1)、同じレベルにあり得ます(- がインデントとして数えられるため、パターン 2)です。どちらも有効で、1 つを選び、一貫させましょう。マッピングのシーケンスでは、アイテムのすべてのキーが、- の後の最初のキーと整列しなければなりません。
# 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マルチラインの文字列(Folded と Literal)
Literal ブロックスカラー(|)
書かれたとおりにすべての改行を保つのが、literal ブロックスカラーの | です。(| を越えた量の)インデントが、各行から剥ぎ取られます。デフォルトの chomping(clip)が、1 つの末尾の改行を保ちます。スクリプト、コード、詩、ASCII アートに使われます — literal な改行が重要なところどこでもです。
# | 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 newlinesFolded ブロックスカラー(>)
単一の改行をスペースに変え、行を段落へ結合するのが、folded ブロックスカラーの > です。リテラルの改行になるのが、空行です。ブロックのコンテンツより深くインデントされた行が、リテラルに保たれます(散文内のコードのサンプルに有用)。
# > 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 です:1 つを保つのが、clip(デフォルト、指示子なし)、すべてを取り除くのが、strip(-)、すべてを保つのが、keep(+)です。指示子が、| か > の直後に来ます(例:|-、|+、>-、>+)。インラインで使われる文字列には strip が有用で、ソースに正確に一致するのが、(まれな)keep です。
# Default (clip): single trailing newline
text: |
line1
line2
# Result: "line1\nline2\n"
# Strip (-): remove ALL trailing newlines
text_strip: |-
line1
line2
# Result: "line1\nline2"
# Keep (+): keep ALL trailing newlines
text_keep: |+
line1
line2
# Result: "line1\nline2\n\n\n"
# Same applies to folded scalars
folded_keep: >+
folded
text
インデントの指示子
ブロックスカラーのコンテンツが空白で始まるとき、数字(例:|2)でコンテンツのインデントを明示的に指定しなければなりません。構造に属する対コンテンツに属する、いくつのインデントのスペースか示すのが、その数字です。chomping と組み合わせましょう:|2-、>4+ などです。まれに必要ですが、必要なときには不可欠です。
# When the first line starts with spaces, you must
# tell YAML the content indentation explicitly
# Without indicator (ambiguous):
# content:
# indented_line # is the leading space content or not?
# With explicit indentation indicator (digit after | or >)
literal: |2
hello
world
# The "2" means: content is indented 2 spaces past the indicator
# So 4 spaces of indentation = 2 content + 2 extra
# Combined with chomping (order: indent then chomp)
text: |2-
no trailing newline
# Folded with explicit indent
folded: >4
paragraph with
explicit indent
# Most of the time you don't need this — only when
# content legitimately starts with spaces素のマルチラインの文字列
複数行にまたがれるのが、素のスカラーと引用されたスカラーで、改行がスペースへ折りたたまれます(> に似ていますが、暗黙的です)。改行がコンテキストと特殊文字に依存するため、これが脆いです。自明でない任意のマルチラインのテキストのためには、明示的な |(literal)か >(folded)のブロックスカラーを優先しましょう。
# 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 textFold 対 Literal の選択
経験則:改行が重要なとき(スクリプト、設定ファイル、コード)には | を使い、読みやすいマルチラインのソースだが結合された段落が欲しいとき(説明、ドキュメント)には、> を使いましょう。文字列がインラインで使われるとき、末尾の改行を剥ぎ取るのが、|- です。
# Use | (literal) when newlines matter:
script: |
#!/bin/bash
set -e
echo "Step 1"
echo "Step 2"
config_file: |
[default]
region=us-east-1
output=json
# Use > (folded) when you want readable source
# but a single paragraph string:
description: >
This service handles user authentication
and session management. It talks to the
PostgreSQL database and Redis cache.
# Use |- or >- to strip trailing newline
# (useful for inline string usage):
inline_script: |-
echo hello
# Use plain single-line for short strings
short: hello worldアンカーとエイリアス
アンカーの定義(&)
ノード(マッピング、シーケンス、スカラー)上にアンカーを定義するのが、&name です。その位置の値をアンカーが変えず、再利用のためにノードをラベル付けるだけです。名前により、アンカーされたノードを参照するのが、エイリアス(*name)です。文書内で使われる前に、アンカーが定義されなければなりません。
# &name defines an anchor on a node
defaults: &defaults
adapter: postgres
host: localhost
port: 5432
# The anchor marks the node so it can be reused
# The value is still assigned normally
production:
database: *defaults
# *defaults is an alias — references the anchored node
# Anchors on scalars
version: &ver "1.0.0"
current: *ver
# Anchors on sequences
colors: &colors
- red
- green
- blue
primary: *colorsエイリアスの使用(*)
以前にアンカーされたノードを参照するエイリアスであるのが、*name です。エイリアスが、元のものと同一性を共有します(ほとんどのパーサーで同じオブジェクトです)。文書スコープされるのが、anchors/aliases です --- 文書の境界をまたいで参照できません。上書きを重ねるには、<<(マージキー)と組み合わせましょう。
# Define once, reuse by alias
base: &base
image: nginx:1.25
restart: always
web:
<<: *base
ports:
- "80:80"
api:
<<: *base
ports:
- "8080:8080"
environment:
- DEBUG=true
# Aliases reference the SAME object (by identity)
# In most parsers, mutating one mutates the other
# (though YAML itself is read-only)
# Aliases can't span documents
# Each document has its own anchor namespaceアンカーのスコープ
自身の文書にスコープされ、任意のエイリアスが参照する前に定義されなければならないのが(前方参照なし)、アンカーです。同じアンカーを複数のエイリアスが参照できます。エイリアスのエ イリアスが機能し — 推移的に解決されます。エラーであるのが、文書をまたぐ参照です。
# Anchors are scoped to a single document
---
# Document 1
shared: &shared
key: value
use: *shared # works
...
---
# Document 2 — &shared is NOT visible here
other: *shared # ERROR: unknown anchor
# Anchors must be defined before the alias
# (forward references are not allowed)
bad: *later # ERROR
later: &later value
# Multiple aliases to the same anchor are fine
template: &tpl
timeout: 30
use1: *tpl
use2: *tpl
use3: *tpl
# Aliasing an alias is allowed
a: &a value
b: &b *a
c: *b # resolves to "value"アンカーされた値の上書き
エイリアス(*name)がノード全体を置き換えるため、部分的に上書きできません。アンカーされたマッピングの個々のキーを上書きするには、merge キーの << を使い、アンカーされたマッピングをマージし、その後、キーを加えるか上書きしましょう。設定の合成の標準のパターンが、これです。
# 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シーケンスのアンカー
シーケンス全体、個々のシーケンスのアイテム、シーケンスの内側のマッピングを、アンカーがラベル付けできます。共通のフィールドを共有するため、似たレコードのシーケンス(例:サービスの定義)で特に有用なのが、<< の merge のパターンです。個々のアイテムをアンカーするのが、- &name value です。
# Anchors work on sequence items too
common: &common
enabled: true
log: stdout
services:
- name: web
<<: *common
port: 80
- name: api
<<: *common
port: 8080
- name: worker
<<: *common
queue: jobs
# Anchoring a whole sequence
endpoints: &endpoints
- /health
- /metrics
- /ready
monitoring:
checks: *endpoints
# Anchoring individual sequence items
list:
- &first one
- two
- *first # "one" againアンカーの注意点
アンカーには注意点があります:エイリアスが同一性を共有し(可変のパーサーで 1 つのミューテートがすべての参照に影響します)、認知的なオーバーヘッドを加え、(JSON 出力を含む)ほとんどのシリアライザがそれらを素のコピーへ展開します。本物の再利用(テンプレート、デフォルト)のためにアンカーを使い、マイクロ最適化のためではありません。
# Caveat 1: shared identity can surprise you
defaults: &defaults
list: [1, 2, 3]
a: *defaults
b: *defaults
# In mutable parsers, a.list and b.list are the SAME list.
# Editing a.list also changes b.list.
# Caveat 2: anchors add cognitive overhead
# Overuse makes YAML hard to read and trace.
# Caveat 3: not all tools preserve anchors on output
# Many serializers expand aliases to plain copies.
# Caveat 4: JSON output loses anchors entirely
# (JSON has no anchor concept).
# Caveat 5: anchors don't work across documents
---
doc1: &x value
use1: *x
---
doc2: *x # ERROR
# Prefer anchors for genuine reuse, not micro-optimization.マージキー(<<)
基本のマージ(<<)
マッピング(通常はエイリアス)を取り、そのキーと値のペアを現在のマッピングへマージするのが、merge キーの << です。現在のマッピングで明示的に設定されたキーが、マージされたものを上書きします。YAML での設定の継承の標準のパターンが、これです。
# << merges a referenced mapping into the current one
defaults: &defaults
adapter: postgres
pool: 5
timeout: 5000
development:
<<: *defaults
database: myapp_dev
host: localhost
production:
<<: *defaults
database: myapp_prod
host: db.example.com
pool: 20 # override
# Result for development:
# adapter: postgres
# pool: 5
# timeout: 5000
# database: myapp_dev
# host: localhost複数のマージ
エイリアスのフローシーケンス([*a, *b, *c])を渡すことで、複数のマッピングをマージできるのが、<< です。マージが左から 右へ適用され、重複キーのために、後のマージが早いものを上書きします。マッピング内の明示的なキーが、任意のマージされたキーに常に勝ちます。複数の << のエントリも許されます。
# << can merge multiple mappings (sequence value)
base: &base
logging: info
retries: 3
security: &security
auth: required
tls: true
service: &service
port: 8080
host: 0.0.0.0
# Merge multiple in one go
production:
<<: [*base, *security, *service]
environment: prod
port: 80 # override service.port
# Later merges override earlier ones for the same key.
# Explicit keys always win over merges.
# You can also have multiple << entries:
combined:
<<: *base
<<: *security
custom: value上書きと優先順位
マージの優先順位:マッピング内の明示的なキーが常に勝ちます。マージされたマッピングの間では、同じキーのために、シーケンスの後のものが早いものを上書きします。これを、デフォルト → ロール固有 → インスタンス固有の上書きをきれいに重ねるのに使いましょう。
# Explicit keys override merged keys
template: &template
port: 8080
log: info
timeout: 30
instance:
<<: *template
port: 9090 # overrides template.port
log: debug # overrides template.log
host: example.com # added
# Final: {port: 9090, log: debug, timeout: 30, host: example.com}
# Precedence: explicit > later merge > earlier merge
a: &a
k: from_a
x: 1
b: &b
k: from_b
y: 2
result:
<<: [*a, *b]
k: explicit # wins over both a and b
# Final: {k: explicit, x: 1, y: 2}アンカーでのマージのパターン
Docker Compose と同様の設定ファイルの基本パターンであるのが、merge+anchor のパターンです:デフォルトのアンカーを定義し、各サービスがそれをマージし、個々のフィールドを上書きします。サービスごとのカスタマイズを犠牲にせず、設定が DRY に保たれます。
# Common pattern: anchor templates, merge + override
defaults: &defaults
image: nginx:1.25
restart: always
logging:
driver: json-file
services:
web:
<<: *defaults
ports: ["80:80"]
api:
<<: *defaults
image: node:20 # override
ports: ["8080:8080"]
environment:
NODE_ENV: production
worker:
<<: *defaults
image: worker:latest
command: ["./run.sh"]
# This is the bread-and-butter of Docker Compose files
# — share base config, override per service.マージの限界
マッピングにのみ機能するのが、merge キーの << です — シーケンスとスカラーはマージできません。浅いのが、merge です:現在のノードのネストしたマッピングが、マージされたものを完全に REPLACES します(deep merge なし)。deep merge のためには、データを再構築するか、アプリケーションのコードで行いましょう。
# << 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.2 のコアのスペックから取り除かれた YAML 1.1 の拡張であるのが、<< の merge キーです。実際には、ほとんどのパーサーが(PyYAML、js-yaml、ruamel、SnakeYAML)まだサポートしますが、厳密な 1.2 のパーサーが拒否します。今日使えますが、非標準であることを知りましょう。新しい形式のためには、本物の継承を持つ設定言語(Cue、Jsonnet、Dhall)を考えましょう。
# IMPORTANT: the << merge key was REMOVED in YAML 1.2
# It was a YAML 1.1 feature.
# In practice, many parsers still support it:
# - PyYAML: supports (1.1 mode)
# - js-yaml: supports (opt-in)
# - ruamel.yaml: supports
# - SnakeYAML: supports
# - LibYAML: supports
# But strict YAML 1.2 parsers reject it:
# new_yaml_1_2_strict:
# <<: *template # ERROR in strict 1.2
# Recommendation:
# - Use << for now (widely supported)
# - Document that your files rely on it
# - For new formats, consider composition in code
# or a config language with proper inheritance
# (e.g. Dhall, Cue, Jsonnet)
# Alternative without <<:
# just duplicate or use application-level templating文書マーカーとディレクティブ
単一文書
任意のマーカーなしで問題なく機能するのが、単一の YAML 文書です。「これが YAML です」と合図し、素のテキストとあいまいさを解消する慣例であるのが、先頭の --- です。オプションで、単一文書のファイルではめったに使われないのが、... の終了マーカーです。
# A single YAML document needs no markers
key: value
list:
- a
- b
# But a leading --- is a common convention
# to mark "this is YAML, not plain text"
---
key: value
# The trailing ... (end marker) is optional
# for a single document
key: value
...複数文書(ストリーム)
--- で区切られた文書のシーケンスであるのが、YAML ストリームです。各文書が独立にパースされます。Kubernetes(ファイルごとの複数のオブジェクト)、静的サイトのジェネレータ、ログファイルでよくあるのが、ストリームです。文書を反復するには、パーサーの load_all() か相当物を使いましょう。
# A YAML stream is multiple documents separated by ---
---
name: first
value: 1
---
name: second
value: 2
---
name: third
value: 3
# Each document is independent — anchors don't cross
# Use a parser's load_all() / load_multi() to read them
# Python (PyYAML):
# for doc in yaml.safe_load_all(stream):
# print(doc)
# Common use cases:
# - Kubernetes: multiple objects in one file
# - Blog generators: front matter + content
# - Log files: one record per document
# - CI/CD: multi-step pipelines文書の終了マーカー(...)
文書を明示的に終了させるのが、... のマーカーです。ほとんどの場合オプションですが、コンテンツがあいまいであり得るとき有用です(例 :--- を含む literal ブロック)。ストリーミングのパーサーへ文書の終了を合図するのも、これです。手書きの YAML ではまれですが、プログラマティックな出力でよくあるのが、これです。
# ... explicitly ends a document
---
key: value
...
# Anything after ... is a new document or stream end
# Useful when a document's content might be ambiguous
# without an explicit end:
---
message: |
Some content
---
that looks like a separator
...
---
next: document
# Without ... the parser might think the ---
# inside the literal block is a document separator
# (though block scalars usually prevent this)
# ... is also useful in programmatic output to flushディレクティブ
文書のコンテンツの前に現れ、パーサーを設定するのが、ディレクティブです。バージョンを設定するのが、%YAML で、タグの接頭辞のショートカットを宣言するのが、%TAG です。文書スコープされるのが、ディレクティブです — 次の文書にのみ適用されます。ディレクティブを省き、パーサーのデフォルト(通常は 1.1 か 1.2 のバイモーダル)に頼るのが、ほとんどの設定ファイルです。
# Directives appear at the very top, before content
# %YAML — declare YAML version
%YAML 1.2
---
key: value
# %TAG — declare a tag prefix
%TAG !e! tag:example.com,2024:
---
data: !e!custom value
# Multiple directives are allowed
%YAML 1.2
%TAG !e! tag:example.com,2024:
%TAG !yaml! tag:yaml.org,2002:
---
value: !yaml!str hello
# Directives are document-scoped — they apply to the
# next document only and must be repeated for each.
# Most config files omit directives and use defaults.文書ストリームの例
広く使われるのが、文書ストリームです。1 つのファイルに複数のオブジェクト(Namespace、Deployment、Service)を束ねるのに、Kubernetes がそれらを使います。Helm のテンプレート、CI のログ、静的サイトのジェネレータ(front matter + コンテンツ)も、ストリームを使います。独立であり、自身のディレクティブを持ち得るのが、各文書です。
# 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 で --- を含めるには、ブロックをインデントするか、最初に ... で文書を終了させましょう。同じ行にコンテンツがある --- が、セパレータでなく文書の開始マーカーです。
# 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フロースタイル
フローシーケンス
[ ] を使い、JSON の配列のように振る舞うのが、フローシーケンスです。内側の空白と改行が柔軟です。JSON と違い、末尾のカンマは許されません。短く密度の高いリストに有用です。特殊文字(カンマ、括弧、コロン)を含むアイテムは、引用しましょう。
# 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 と違い)禁止されるのが、末尾のカンマです。短く密度の高いデータにはフローマッピングを使いましょう。より大きい構造には、ブロックスタイルがより読みやすいです。
# 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フローとブロックの混合
文書内で自由に混ぜられるのが、フローとブロックのスタイルです。実用的な規則:構造的な要素にはブロックスタイルを(インデントでより読みやすく)、短いインラインの値(スカラーのリスト、小さいマップ)にはフロースタイルを使いましょう。深くネストしたフローを避けましょう — すぐに読めなくなります。
# 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 レベルのネストの後、読みやすさのためにブロックスタイルに切り替えましょう。深くネストしたフローのブロックの相当物が、人間のメンテナにとってほとんど常に明確です。
# 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 互換の出力のためには、フロースタイルを使いましょう。長いリスト(スキャンしにくい)、深くネストした構造(括弧の壁)、インラインコメントを必要とするものには、フローを避けましょう。疑わしいときは、読みやすさのためにブロックスタイルを優先しましょう。
# 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 しにくいです。バージョン管理された設定には、ブロックスタイルがより友好的です。
# 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)YAML と JSON の変換
JSON は有効な YAML
JSON が厳密なサブセットになるよう設計されたのが、YAML 1.2 です — 任意の JSON 文書が有効な YAML です。ほとんどの YAML パーサーが、喜んで JSON を読みます。逆は真ではありません:コメント、アンカー、マルチ文書ストリーム、ブロックスカラーのような YAML の機能が、有効な JSON ではありません。
# 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 ブロック)です。
# 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 dataJSON から YAML への変換
JSON をパースし、その後、default_flow_style=False(ブロックスタイル)で YAML として dump することで、JSON を YAML へ変換しましょう。YAML が必要としない ところで、JSON の必須の引用が落とされます。数値/ブールに見えるキーに注意しましょう — 文字列の型を保つため、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 preservedYAML から JSON への変換
パースし、その後 JSON serial 化することで、YAML を JSON へ変換しましょう。注意点:コメントとタグが失われ、アンカーが素のコピーへ展開され、マルチ文書ストリームが JSON 配列になる必要があり、YAML の日付が文字列になり得ます。コマンドラインでこれを容易にするのが、yq のようなツールです。
# 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 の両方の消費者が同じデータを読むときや、厳密な型の保存が重要なときに有用です。
# 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.往復の考慮事項
(パースし dump する)YAML の往復は、しばしばコメント、アンカー名、キーの順序、引用のスタイル、フォーマットが失われます。コメントと順序を保存する round-trip モードがあるのが、ruamel.yaml(Python)です。人間が編集する設定のためには、dumper の出力で盲目に上書きせず — 最初に慎重に diff しましょう。
# 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 carefullyYAML のスキーマ
Failsafe スキーマ
最も保守的であるのが、Failsafe スキーマです — str、map、seq だけを認識します。明示的にタグ付けされない限り、すべてのスカラーが文字列です。信頼されていない入力(暗黙の強制の驚きなし)のためや、カスタムスキーマのベースとして有用です。わずかに豊富なスキーマを使うのが、ほとんどの本番のローダーです。
# 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 相互運用や厳密な型の挙動のために使いましょう。
# 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 semanticsCore スキーマ
YAML 1.2 のデフォルトであるのが、Core スキーマです。寛容なパースで JSON を拡張します:hex(0x)、8 進(0o)、2 進(0b)、数値内のアンダースコア、.inf/.nan の float です。true/false だけであるのが(yes/no ではなく)、ブールです。文字列であるのが(推論なし)、日付です。Core か 1.1 互換のバリアントをデフォルトとするのが、ほとんどのモダンなパーサーです。
# 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 対 1.2
yes/no/on/off をブールとして、先頭の 0 の数値を 8 進として扱うのが、(PyYAML のデフォルトの)YAML 1.1 です — 有名なバグの源です(ノルウェーの「no」→ false)。ブールを true/false に制限し、8 進に 0o を使うのが、(現在のスペックの)YAML 1.2 です。常にパーサーのデフォルトをチェックし、あいまいな文字列を引用しましょう。
# 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、先頭ゼロの数値、60 進法のリテラルが、異なるパースをされます。緩和するには:あいまいな文字列を引用し、%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 スキーマを。設定ファイルのためには、あいまいな文字列(「no」、「010」など)の引用付きの 1.2 Core が、最も安全な組み合わせです。
# 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 cleanlyYAML の Lint と検証
yamllint
標準の YAML リンターであるのが、yamllint です(Python)。構文のエラー、インデントの問題、末尾の空白、欠落した文書マーカーなどを捉えます。YAML の問題を早く捉えるため、CI と pre-commit フックで使いましょう。警告をエラーとして扱うのが、厳格モード(-s)です。
# 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 -Lint の設定
.yamllint.yml で yamllint を設定しましょう。プロファイル(default か strict)を extend し、その後、個々のルールを上書きしましょう:インデント、行の長さ、引用のスタイル、コメント、末尾のスペース、文書マーカーです。チームのスタイルに合わせ調整しましょう。一貫して強制するため、CI で走らせましょう。
# .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 のエラー:インデントのためのタブ(スペースのみが許されます)、後続のスペースのないコロン、(マッピングとしてパースされる)コロンのある引用されていない文字列、フロースタイルの末尾のカンマ、一貫しないインデント、重複キーです。これらすべてを自動的に捉えるのが、リンターです。
# 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タブ対スペースのエラー
YAML の構造的なインデントのためのタブは厳格に禁止されます — パースエラーの第 1 位の原因です。文字列の値(ブロックスカラー、引用された文字列)の内側のタブは構いません。YAML ファイルのため、スペースを使うようエディタを設定しましょう(expandtab)。問題の行を検出するのが、grep -P '\t' です。
# 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)重複キーの検出
推奨されず、よくあるバグの源であるのが(サイレントな last-wins の上書き)、マッピング内の重複キーです。key-duplicates のルールで(デフォルトで有効)、それらを検出するのが、yamllint です。よくある原因:コピーペーストのエラーと悪いマージコンフリクトの解決です。早く捉えるため、常に CI で lint しましょう。
# 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.スキーマの検証
(YAML が JSON のスーパーセットであるため機能する)JSON Schema で、YAML の構造を検証しましょう。Kubernetes のためには、kubeval か kubectl --dry-run を使いましょう。一般的な設定のためには、yamllint(構文/スタイル)と jsonschema(構造)か Cue(スキーマ言語)を使いましょう。pre-commit フックと CI へ検証を配線しましょう。
# 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]Docker Compose YAML
サービスの定義
マルチコンテナのアプリを定義するのが、Docker Compose のファイルです。トップレベルのキー:version、services、volumes、networks、configs、secrets です。image/build、ports、volumes、environment、depends_on、restart ポリシーを、各サービスが定義します。トップレベルで宣言された volumes が、名前付きで永続化されます。
# 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:Volumes と Networks
bind マウント(host:container)、(トップレベルの volumes で宣言された)named、anonymous であり得るのが、Compose の volumes です。マウントを読み取り専用にするのが、:ro の接尾辞です。サービスを分離するのが、networks で、外部アクセスをブロックするのが、internal: true です。コンテナの再作成をまたいでデータを永続化するのが、named volumes です。
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環境変数
3 つの env-var のスタイルを Compose がサポートします:list(KEY=value)、map(KEY: value)、env_file です。パース時に、ホストのシェルか .env ファイルから補間されるのが、${VAR} で、デフォルトを提供するのが、${VAR:-default} です。リテラルの $ をエスケープするのが、$$ です。自動的にロードされるのが、プロジェクトのルートの .env ファイルです。
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_$5Depends、Healthchecks、Restart
依存の healthcheck が通るまで開始を待つのが、condition: service_healthy 付きの depends_on です。test(CMD か CMD-SHELL)、interval、timeout、retries、start_period を、healthchecks が使います。restart のポリシー:no、always、unless-stopped(再起動を生き延びますが、手動の停止を尊重します)、on-failure です。
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 exitOverride ファイル
ベースの上に override ファイルをマージするのが、Compose です。自動的に適用されるのが、docker-compose.override.yml です。deep-merge されるのが(override が勝ちます)、マッピングで、通常は(追加されず)置き換えられるのが、シーケンスです — ports/volumes に注意しましょう。環境固有の設定のために、明示的なファイルの順序を指定するのが、-f のフラグです。
# 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 orderProfiles と Compose の機能
--profile のフラグで、サービスに(例:debug、test、ci)オプトインさせてくれるのが、profiles です。他の v3 の機能:init(正しい PID 1 のシグナル処理)、extends(別のサービスからの継承)、configs と secrets(ファイルとしてマウントされます)、deploy(Swarm の配置/レプリカ/リソース)です。複数の環境のために 1 つの compose ファイルを保つのに、profiles が最適です。
# 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.txtKubernetes YAML
オブジェクトの構造
apiVersion、kind、metadata、spec を、すべての Kubernetes オブジェクトが持ちます。group/version であるのが(例:apps/v1、コアには v1)、apiVersion です。name、namespace、labels、annotations を含むのが、metadata です。望まれた状態であるのが、spec で — 現実が spec に一致するよう働くのが、Kubernetes です。システムにより設定されるのが、status です。
# 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)Labels と Selectors
オブジェクトを特定しグループ化するのが、labels で、labels によりクエリするのが、selectors です。等式ベース(key=value)とセットベース(In、NotIn、Exists、DoesNotExist)のセレクタの両方がサポートされます。非識別のメタデータ(説明、連絡先、ツーリングの設定)を保持するのが、annotations です。選択のためのものが labels で、追加の情報のためのものが annotations です。
# 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 Spec
containers、それらの images、ports、(リテラルか secrets/configmaps からの)env vars、(requests/limits の)resources、probes(readiness/liveness)、volumes と volumeMounts を定義するのが、Pod の spec です。最小の配備可能な単位であるのが、Pods ですが、通常は、直接でなく Deployments 経由で作ります。
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: AlwaysDeployment
ReplicaSets と Pods を管理するのが、Deployment です。望まれた数を設定するのが、spec.replicas です。RollingUpdate(デフォルト、maxSurge/maxUnavailable により制御されます)か Recreate であり得るのが、strategy.type です。pods がどう作られるか定義するのが、pod のテンプレート(spec.template)です。kubectl rollout status/undo/history でロールアウトを管理しましょう。
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-appService
ネットワークサービスとして Pods を公開するのが、Service です。内部専用であるのが、type ClusterIP(デフォルト)で、各ノード上で公開するのが、NodePort、クラウドの LB をプロビジョニングするのが、LoadBalancer、DNS の CNAME であるのが、ExternalName です。マッチする pods へトラフィックをルーティングするのが、selector です。service の port を container の targetPort へマッピングするのが(数値か名前付き)、ports です。
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
非機密の設定を保持するのが(文字列かファイル)、ConfigMaps で、機密データを保持するのが(data では base64 エンコードされ、stringData では平文です)、Secrets です。env vars(valueFrom)経由や volumes としてマウントされることで消費されるのが、両方です。デフォルトで暗号化されないのが、Secrets です — 保存時の暗号化を有効化し、RBAC のアクセスを制限しましょう。
# 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-configCI/CD の設定(GitHub Actions と GitLab CI)
GitHub Actions のワークフロー
.github/workflows/ に住むのが、GitHub Actions のワークフローです。triggers であるのが(push、PR、schedule、workflow_dispatch)、on: です。runs-on + steps を含むのが、jobs です。actions を参照するのが、uses: で、シェルを実行するのが、run: です。${{ }} の構文を使うのが、式です — 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.yml に住むのが、GitLab CI です。パイプラインの順序を定義するのが、stages です。stage、image、script、多くのオプション(only/except、rules、when、artifacts、environment)を、jobs が持ちます。$VAR の構文を使うのが(YAML のブロックスカラーではエスケープが不要)、変数です。クリックでの配備を要求するのが、when: manual です。
# .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マトリックスビルド
異なる変数で複数回ジョブを走らせるのが、マトリックスビルドです。strategy.matrix と include/exclude を使うのが、GitHub Actions です。parallel.matrix を使うのが、GitLab です。1 つの失敗が兄弟をキャンセルするのを防ぐのが、fail-fast: false です。クロスプラットフォーム、マルチバージョンのテストに有用です。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
再利用をサポートするのが、両方のシステムです。uses: で呼ばれる、reusable workflows(workflow_call の trigger)を使うのが、GitHub Actions です。include(project、local、template、remote)を使うのが、GitLab です。共有された CI のロジックの重複を減らすのが、再利用です。ワークフローが合成可能で監査可能に保たれるよう、inputs/secrets を明示的に渡しましょう。
# 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.ymlCI 設定のアンカー
CI の設定での重複を減らすのが、YAML のアンカーです。それらを多用するのが、GitLab CI です:&anchor 付きの隠れたジョブ(.template)を定義し、その後、マージするのが、<<: *anchor です。アンカーをサポートするが、ジョブをまたいで非推奨にするのが(reusable workflows を優先しましょう)、GitHub Actions です。設定が DRY になりますが、追跡しにくくなるのが、アンカーです — 賢明に使いましょう。
# 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 workflowsEnvironments と Secrets
(承認を要求し、ブランチに制限する)配備をゲートし、環境スコープの secrets を保持するのが、GitHub Actions の environments です。${{ secrets.NAME }} 経由で参照されるのが、secrets です。UI で定義される、protected(ブランチ制限)と masked(ログで隠される)の変数を使うのが、GitLab です。secrets を決してログしてはいけません — エラー出力で漏れ得ます。
# 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セキュリティの考慮事項
脱直列化のリスク
!!python/object/apply のようなタグが任意の関数を呼べるため、危険であるのが、YAML の脱直列化です。5.1 の前、デフォルトで安全でなかったのが、PyYAML の yaml.load() です(信頼されていない入力からのコード実行です)。信頼されていない入力には、常に yaml.safe_load() を使いましょう — オブジェクトのインスタンス化のタグを拒否します。類似の危険が、他の言語にあります(SnakeYAML、Psych)。
# 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 loadersafe_load 対 load
常に safe_load(Python)、safe_load(Ruby Psych)、デフォルトの safe スキーマ(js-yaml、Go yaml.v3)を使いましょう。yaml.load() のための明示的な Loader を PyYAML 5.1+ が要求します。標準のタグを許すが任意のオブジェクトを許さないのが、full_load です — 信頼されたファイルにのみ使いましょう。すべてのオブジェクトのインスタンス化のタグを拒否するのが、safe ローダーです。
# 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ローカルタグの悪用
!!python/object なしでも、悪用され得るのが、(!include、!env、!file、!exec、!template の)カスタムタグです。ファイルを読む !include が、パストラバーサル経由で /etc/passwd や .ssh/id_rsa を読むよう仕向けられ得ます。すべてのカスタムコンストラクタを監査しましょう:allowlist に対してパスを検証し、絶対パスと ../ を拒否し、ローダーをサンドボックス化しましょう。
# 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 の参照です)。緩和するには:エイリアスの深さの制限、総サイズの制限、ストリーミングのパーサー、過度のネストの拒否です。深いネスト(スタックオーバーフロー)と巨大なフラットなコレクションにも注意しましょう。
# "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) ドメインの検証(ポートの範囲のようなビジネスルール)です。異なる攻撃を各レイヤーが捉えます。構造を信頼せず — 常に使用前に検証しましょう。
# 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(デフォルトで safe)、Go yaml.v3、Psych.safe_load、SafeConstructor 付きの SnakeYAML、serde_yaml です。明示的な safe ローダーなしの yaml.load を避けましょう。セキュリティパッチのため、最近のバージョンに固定しましょう。カスタムコンストラクタを監査しましょう。ライブラリのセキュリティのドキュメントを読みましょう。
# 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ベストプラクティス
一貫したインデント
一貫して 2 スペースを使い(事実上の標準)、決してタブを使いません。YAML のため、スペースを挿入するようエディタを設定しましょう。一貫性を強制するには、フォーマッタ(prettier、yamlfixer)とリンター(yamllint)を使いましょう。最もよくある 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)には二重引用符を、アポストロフィを持つ literal な文字列には単一引用符を使いましょう。
# 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 対 1.2 のあいまいさ)、コロンのある引用されていない文字列、末尾の空白、CRLF の行末(LF を使いましょう)、BOM(BOM なしの UTF-8 で保存しましょう)、非常に長い行(ブロックスカラーで折り返しましょう)です。これらのほとんどをリンターが捉えます。
# 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 対 1.2 の違いが重要なら、%YAML 1.2 で YAML のバージョンを固定しましょう。スキーマを文書化しましょう:必須/オプションのフィールド、型、デフォルト、範囲を、コメント、JSON Schema のファイル、README でです。設定の検証が再現可能になるよう、コードでスキーマのバージョンを固定しましょう。オンボーディングの摩擦と設定のエラーが減ります。
# 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 での Lint
(GitHub Actions、GitLab CI の)CI へと、pre-commit フックへ、YAML の lint を配線しましょう。構文/スタイルには yamllint を、フォーマットには prettier を使いましょう。インラインの lint とスキーマの検証を提供するのが、エディタの統合(VS Code YAML 拡張、yaml-language-server)です。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 を編集するため、読みやすさが重要です。
# 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.高度な機能
複雑なマッピングのキー
複雑なキー(キーとして使われるマッピングかシーケンス)を印付けるのが、? の指示子です。(例:region+instance による価格の)ルックアップテーブルに有用です。注意:多くのシリアライザが複雑なキーを保存せず、出力時に文字列化し得ます。シンプルさとツールの互換性のため、素の文字列のキーに留まるのが、ほとんどの設定ファイルです。
# 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.Sets(!!set)
キーが要素で、値が null であるマッピングであるのが、YAML の set(!!set)です。ネイティブの Set 型へマッピングするのが、いくつかのパーサーです。一意のコレクション(ロール、パーミッション)を宣言するのに使いましょう。注意:Set 型を持たないのが JSON であるため、JSON の変換が null の値を持つオブジェクトを生成します。!!set のタグを保存しないのが、すべてのシリアライザではありません。
# 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(ordered mapping)です。タイムライン、順序付きの設定、順序が意味的に重要なところに有用です。とにかく通常のマッピングの順序を保存するのが(Python の dict 3.7+、Ruby の Hash)、モダンなパーサーですが、ランダムであるのが、Go の maps です — そこで順序を明示するのが、!!omap です。
# 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)
YAML で base64 としてバイナリデータをエンコードするのが、!!binary です。ネイティブのバイト(Python の bytes、Ruby の ASCII-8BIT の文字列)へデコードするのが、パーサーです。小さい画像かアイコンを直接埋め込むのに有用です。大きなバイナリデータのためには、パスか URL による参照を優先しましょう。folded(>)か literal(|)のブロックスカラーで機能するのが、マルチラインの base64 です。
# 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 を使いましょう。副作用(ファイルの読み取り、サブプロセスの呼び出し)のためにコンストラクタを常に監査しましょう — 信頼されていない入力で悪用され得ます。
# 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 の機能と未来
JSON を厳密なサブセットにし、ブールを true/false に制限し、8 進に 0o を採用したのが、YAML 1.2 です。コアのスペックから取り除かれたのが、merge キーの << ですが、今も広くサポートされます。スペックを明確化したのが、YAML 1.2.2(2021)で、開発中が、1.3 です。バージョンを固定し、あいまいな文字列を引用し、複雑な設定のためには Cue/Dhall/Jsonnet を考えることで、将来に備えましょう。
# 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.関連する YAML スニペット
Copy-paste ready code for common tasks.
Scalars
Strings, numbers, booleans, null, and dates.
Sequences and Mappings
Lists and key-value maps.
Anchors and Aliases
Reuse nodes with anchors, aliases, and merge keys.
Multi-Document
Several documents in one stream.
Tags
Explicit type tags for custom resolution.
Flow Style
Inline JSON-like sequences and mappings.
Block Style
Indentation-based nesting.
Schema Types
How YAML 1.1 and 1.2 resolve scalars.
Was this helpful?