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.

The standard tags

TagFull URI suffixExampleResult
!!strtag:yaml.org,2002:str!!str 42"42"
!!int...:int!!int "7"7
!!float...:float!!float "3"3.0
!!bool...:bool!!bool "yes"True
!!null...:null!!null ""None
!!seq...:seq!!seq [1, 2][1, 2]
!!map...:map!!map {a: 1}{"a": 1}
!!set...:set!!set {a, b}a set, values null
!!omap...:omap!!omap [{a: 1}]ordered pairs
!!binary...:binary!!binary "R0lG"b"GIF"
!!timestamp...:timestamp!!timestamp 2024-01-15a date
!!merge...:merge<<:merge key

!!str, !!int, !!float, !!bool, !!null, !!seq, and !!map are the 1.2 core schema. Everything else on that list is a 1.1 type that survives as a widely implemented extension, so support varies by parser.

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

Custom tags

A single ! introduces an application tag. The YAML parser records it and the application decides what it means, so a generic loader cannot construct it.

Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "${AWS::StackName}-assets"
      Tags:
        - Key: arn
          Value: !GetAtt MyBucket.Arn
      Policy: !Ref BucketPolicy

CloudFormation defines !Ref, !GetAtt, !Sub, !Join, !If, !Select, !ImportValue, and !FindInMap. Each is shorthand for a one-key mapping, so !Ref X is exactly {"Ref": "X"}.

yaml.safe_load on that file raises:

ConstructorError: could not determine a constructor for the tag '!Sub'

To read it you register the tags yourself:

import yaml

class CfnLoader(yaml.SafeLoader):
    pass

def multi(loader, suffix, node):
    return {suffix: loader.construct_scalar(node)}

CfnLoader.add_multi_constructor("!", multi)
doc = yaml.load(open("template.yaml"), Loader=CfnLoader)

cfn-lint and the AWS SAM CLI ship their own version of this. Verified output for the two lines above is {'BucketName': {'Sub': '${AWS::StackName}-assets'}, 'Policy': {'Ref': 'BucketPolicy'}}.

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"]
CallSafety
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

WrittenExpands to
!!strtag: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
! alonethe "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.