YAML Cheatsheet
Tags and Explicit Types
Use this YAML reference while you build software engineering projects, review code, or refresh the syntax you reach for most.
Overriding the resolver
A tag forces a node's type instead of letting the regex resolver guess. !!name
is the shorthand for a standard tag, !name for an application-specific one.
a: !!str 42 # the string "42", not the int 42 b: !!int "7" # the int 7, from a quoted source c: !!float "3" # 3.0 d: !!bool "yes" # True, even under a 1.2 parser
Parsed: {'a': '42', 'b': 7, 'c': 3.0, 'd': True}. In practice quoting is shorter
than !!str and works in more places, so tags are mostly something you read
rather than write.
!!set, !!omap, and !!binary
tags: !!set ? web ? prod ? api ordered: !!omap - first: 1 - second: 2 logo: !!binary | R0lGODlhDAAMAIQAAP//9/X1 6unp5WZmZgAAAOfn515eXg==
That logo loads as the bytes value b"GIF89a\x0c\x00\x0c\x00...", and
ordered loads as the list of pairs [('first', 1), ('second', 2)]. !!set loads
as a Python set and also accepts the flow spelling !!set {a, b}. !!binary is
base64, and it is the only sanctioned way to put bytes in YAML. Note
that Kubernetes Secret does not use !!binary, it uses a plain string field
whose value happens to be base64, so do not add the tag there.
yaml.load is a security hole
The Python !!python/* tags let a document construct arbitrary objects, and
yaml.load without a Loader argument enabled them by default for years.
# with the unsafe loader, this runs os.system !!python/object/apply:os.system ["id"]
| Call | Safety |
|---|---|
yaml.safe_load(s) | safe. Core types only. Use this. |
yaml.load(s, Loader=yaml.SafeLoader) | same thing, explicit |
yaml.load(s, Loader=yaml.FullLoader) | blocks known RCE, still not for untrusted input |
yaml.load(s) | since PyYAML 5.1 warns and defaults to FullLoader |
yaml.load(s, Loader=yaml.UnsafeLoader) | arbitrary code execution |
yaml.unsafe_load(s) | same, arbitrary code execution |
ruamel.yaml.YAML(typ="safe") | safe |
ruamel.yaml.YAML(typ="unsafe") | arbitrary code execution |
Rule: safe_load for everything you did not write. CVE-2017-18342 exists
because yaml.load was the obvious-looking call. In Go, yaml.Unmarshal has no
equivalent hole because it only fills a declared struct. In Ruby, YAML.load was
made safe by default in Psych 4 (Ruby 3.1), and YAML.unsafe_load is the opt-in.
Verbose and shorthand tag forms
| Written | Expands to |
|---|---|
!!str | tag:yaml.org,2002:str |
!<tag:yaml.org,2002:str> | the same, verbose form |
!foo | !foo, a local tag |
!e!foo after %TAG !e! tag:x.com,2024: | tag:x.com,2024:foo |
! alone | the "non-specific" tag |
You will see the verbose !<...> form in machine-generated YAML and essentially
never need to type it. !<tag:yaml.org,2002:str> 42 gives "42", identical to
!!str 42. The bare ! is under-implemented and behaves inconsistently across
parsers (PyYAML still resolves ! 123 to the int 123), so use quotes or !!str
when you want a string.