Link Search Menu Expand Document

YAML Cheat Sheet

YAML Syntax Examples

YAML Scalars

Scalar types

a: 1        # integer          
a: 1.234    # float      
b: 'abc'    # string        
b: "abc"                   
b: abc                     
c: false    # boolean type 
d: 2015-04-05   # date type

Enforcing strings

b: !str 2015-04-05

YAML Sequences

Simple sequence

   - 132
   - 2.434
   - 'abc'

Sequence of sequences

   - [1, 2, 3]
   - [4, 5, 6]

YAML Hashes

Nested hash

     subsubkey1: 5
     subsubkey2: 6
     somethingelse: 'Important!'

Hash with JSON syntax (mixing is possible)

 my_hash: {nr1: 5, nr2: 6}

YAML HereDoc (multiline strings)

Block notation: Newlines become spaces

   Arbitrary free text
   over multiple lines stopping only
   after the indentation changes...

Literal style: Newlines are preserved

content: |
   Arbitrary free text            
   over "multiple lines" stopping 
   after indentation changes...   

+ indicator: Keep extra newlines after the block

content: |+                      
   Arbitrary free text with newlines after

- indicator: remove extra newlines after block

content: |-
   Arbitrary free text without newlines after it

folded style: folded newlines are preserved

 content: >
   Arbitrary free text
   over "multiple lines" stopping
   after indentation changes...

Note that YAML heredocs are the way to escape special characters:

    url: ""        # sub key "url" with value 'https://...'

 code: |-                             # versus key "code" having value 'url: "https://..."'
    url: ""

There is a good online previewer for the different heredoc modes:

Multiple Documents

A YAML file can have multiple documents, this is why every document needs to start with a “—” line

 content: doc1
 content: doc2

This also means YAML parsers might return multiple documents!

Content References (Aliases)

   - &ref Something to reuse
   - *ref      # Literal "Something to reuse" is inserted here!

Merging Keys

Imagine some default properties for a hash like these

     dir: /usr/local
     owner: root
     enabled: false

Use them in another hash using “«: *reference”

 # Derive settings for 'my_app' from default and change install::owner
 # and add further setting "group: my_group"
   <<: *default_settings
     owner: my_user
     group: my_group

Complex Mapping

 ? - key                          
   - value                        

Note: key and value can be multiple, complex structures that you could not realize with the hash syntax!