YAML Syntax
YAML is the configuration language of DevOps: Kubernetes manifests, Helm values, GitHub Actions and GitLab CI workflows, Docker Compose files, Ansible playbooks, OpenAPI specs. It was designed to be easy for people to read, and it is, until indentation or an unquoted value means something you did not intend. This lesson covers the syntax you need to read and write those files confidently; the next one collects the traps.
Every session shows the YAML next to what a parser makes of it. yq -o=json (yq 4.54) converts YAML to JSON, which
makes the structure explicit.
Mappings, sequences and scalars
YAML has three kinds of node: mappings (key/value pairs, JSON objects), sequences (lists, JSON arrays) and scalars (strings, numbers, booleans, null). Nesting is expressed with indentation by spaces:
cat > app.yaml <<'YAML'
# A comment runs to the end of the line
name: shop-api # a string, no quotes needed
replicas: 3 # an integer
public: true # a boolean
owner: null # null (also ~ or an empty value)
image: # a nested mapping
repository: registry.example.com/shop-api
tag: "1.4.2" # quoted: stays a string
ports: # a sequence of scalars
- 8080
- 9090
env: # a sequence of mappings
- name: LOG_LEVEL
value: info
- name: REGION
value: eu-west-1
YAML
yq -o=json app.yaml{
"name": "shop-api",
"replicas": 3,
"public": true,
"owner": null,
"image": {
"repository": "registry.example.com/shop-api",
"tag": "1.4.2"
},
"ports": [
8080,
9090
],
"env": [
{
"name": "LOG_LEVEL",
"value": "info"
},
{
"name": "REGION",
"value": "eu-west-1"
}
]
}
Rules that matter:
- Indentation is spaces only. The number of spaces is up to you (2 is the convention in DevOps files), but every item at one level must line up exactly.
-starts a sequence item. Items of a list inside a mapping may be indented under the key or level with it; bothports:\n - 8080andports:\n- 8080are valid, andyamllintcan enforce one style.- In
- name: LOG_LEVELthe dash starts an item and the item is a mapping;valuemust line up withname. - A colon needs a space after it to be a key separator:
url: http://xis fine,key:valueis just a string.
Flow style: JSON inside YAML
YAML also has a compact flow style with [ ] and { }. Any JSON document is (almost always) valid YAML too:
cat > flow.yaml <<'YAML'
ports: [8080, 9090]
labels: {app: shop-api, tier: backend}
resources: {"limits": {"cpu": "500m", "memory": "256Mi"}}
YAML
yq -o=json -I=0 flow.yaml
echo "--- and back to block style:"
yq -P flow.yaml{"ports":[8080,9090],"labels":{"app":"shop-api","tier":"backend"},"resources":{"limits":{"cpu":"500m","memory":"256Mi"}}}
--- and back to block style:
ports:
- 8080
- 9090
labels:
app: shop-api
tier: backend
resources:
limits:
cpu: 500m
memory: 256Mi
Flow style is handy for short lists; for anything nested, block style reads better and diffs better.
Strings: plain, single and double quotes
Most strings need no quotes. Quote them when they would otherwise be read as another type, or contain characters
with a meaning in YAML (: , #, a leading -, *, &, !, {, [, @, `):
cat > strings.yaml <<'YAML'
plain: hello world
colon_in_value: http://example.com:8080/health
hash_needs_quotes: "color #fff"
comment_instead: color #fff
single: 'no escapes here: \n stays as two characters, '' is a quote'
double: "escapes work: tab\there, newline\nhere, unicode é"
leading_star: "*.example.com"
YAML
yq -o=json strings.yaml{
"plain": "hello world",
"colon_in_value": "http://example.com:8080/health",
"hash_needs_quotes": "color #fff",
"comment_instead": "color",
"single": "no escapes here: \\n stays as two characters, ' is a quote",
"double": "escapes work: tab\there, newline\nhere, unicode é",
"leading_star": "*.example.com"
}
- Single quotes are literal; the only escape is
''for a quote. - Double quotes understand backslash escapes like JSON (
\n,\t,\",é). #(space, hash) starts a comment even in the middle of an unquoted value, which silently truncatedcomment_instead.- An unquoted value starting with
*is an alias reference (YAML Gotchas), so a wildcard hostname must be quoted.
Multi-line strings: | and >
Scripts in CI files, certificates and config snippets are multi-line strings. A literal block (|) keeps the
newlines; a folded block (>) joins lines with spaces and keeps blank lines as newlines. A suffix controls the
final newline: none keeps one, - strips it, + keeps all trailing newlines:
cat > blocks.yaml <<'YAML'
script: |
set -euo pipefail
make test
make build
description: >
This service handles
checkout and payments.
It is owned by team-core.
single_line: >-
a long line folded
for readability
YAML
yq -o=json blocks.yaml{
"script": "set -euo pipefail\nmake test\nmake build\n",
"description": "This service handles checkout and payments.\nIt is owned by team-core.\n",
"single_line": "a long line folded for readability"
}
The indentation of the first line sets the block's indentation; it is removed from every line. Use | for scripts
(GitHub Actions run:, GitLab script:, Kubernetes ConfigMaps with config files) and >- for long prose values.
Several documents in one file
--- separates documents in one stream. Kubernetes manifests rely on it to put a Deployment and its Service in one
file, and kubectl apply -f applies each document:
cat > manifests.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-api
---
apiVersion: v1
kind: Service
metadata:
name: shop-api
YAML
yq '.kind + "/" + .metadata.name' manifests.yaml
echo "--- documents: $(yq -N 'document_index' manifests.yaml | wc -l)"Deployment/shop-api
---
Service/shop-api
--- documents: 2
yq runs the expression once per document and separates the results with ---; -N (--no-doc) leaves the
separators out. ... on its own line ends a document without starting another; you will
rarely need it.
Tabs and bad indentation
Tabs are not allowed for indentation, and inconsistent indentation is either an error or, worse, a different structure. Parsers say where they gave up:
printf 'image:\n\trepository: shop-api\n' > tabs.yaml
yq . tabs.yaml; echo "-> status $?"
printf 'env:\n - name: A\n value: x\n' > misaligned.yaml
yq . misaligned.yaml; echo "-> status $?"Error: bad file 'tabs.yaml': go-yaml load error in scanner (while scanning for the next token) at L2.C1: found character that cannot start any token
-> status 1
Error: bad file 'misaligned.yaml': go-yaml load error in parser (while parsing a block collection) at L2.C3-L3.C4: did not find expected '-' indicator
-> status 1
Configure your editor to insert spaces in YAML files, show whitespace, and run yamllint in CI; both errors above would never reach a cluster.
Test yourself
How is nesting expressed in YAML block style?
- With braces
- With indentation using spaces
- With tabs
- With semicolons
What value does note: color #fff give note?
- "color #fff"
- "color", because
#starts a comment - an error
- null
Which block scalar keeps line breaks exactly, as needed for a shell script?
- >
- |
- >-
- ---