YAML is a human-friendly data format used by Ansible, Docker Compose, Kubernetes, GitHub Actions and CI/CD pipelines. Any valid JSON is also valid YAML (1.2).
Indentation uses spaces only. Tabs are forbidden and cause a syntax error.
The number of spaces is up to you (2 is the common choice), but it must be consistent within a block.
key: value: a space after the colon is required.
- item: a list item.
# starts a comment.
--- starts a document. It is optional, but yamllint expects it.
Sample.yml
---
# Team members
workers:
- name: Martin
job: Developer
skills:
- lisp
- fortran
- name: Tabitha
job: Developer
skills: [erlang, python] # flow style, same as a list
- name: Bob
job: DevOps
active: true
manager: null
skills: []
...
Quotes are usually optional, but quote values that look like something else. Ansible and PyYAML follow YAML 1.1, where these values change type:
"double quotes" support escapes: "line 1\nline 2".
'single quotes' do not: '\n' stays as the two characters \n.
literal: | # keep line breaks
line 1
line 2
folded: > # join lines with spaces
This is a long
sentence.
The same - / + modifiers work with >.
&name defines an anchor, *name reuses it, and <<: merges a map:
---
admin: &admin Bob
owner: *admin # owner = Bob
defaults: &defaults
adapter: postgres
host: localhost
development:
<<: *defaults
database: dev_db
production:
<<: *defaults
host: db.example.com # overrides the value from defaults
database: prod_db
The merge key << is a YAML 1.1 feature. PyYAML and Ansible support it, but some parsers do not.
sudo apt install yamllint
yamllint Sample.yml
Optional .yamllint in the project directory:
---
extends: default
rules:
line-length:
max: 120
truthy:
allowed-values: ['true', 'false'] # warn on yes/no/on/off
Check how a file is actually parsed by converting it to JSON:
sudo apt install python3-yaml
python3 -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))' < Sample.yml