YAML Quick Reference
Everything you need day‑to‑day – configuration, Kubernetes, Docker Compose, and more.
YAML Basics
Key Concepts
- YAML – YAML Ain't Markup Language
- Human‑readable data serialisation format
- Case‑sensitive
- Whitespace‑sensitive (indentation matters)
- Uses spaces (tabs not allowed)
- File extensions:
.yaml,.yml - Common in: Kubernetes, Docker Compose, Ansible, CI/CD
Syntax Rules
- Key‑Value:
key: value(space after colon) - Lists:
- item(hyphen + space) - Indentation: 2 spaces (common), 4 spaces, or any consistent amount
- Comments:
# This is a comment - No trailing commas
- Valid UTF‑8 (supports Unicode)
Basic Structure
# This is a comment key: value number: 42 float: 3.14 boolean: true null_value: null # Nested structure (2 spaces) person: name: Alice age: 25 address: street: 123 Main St city: New York # List (array) fruits: - apple - banana - orange # List of objects users: - name: Alice age: 25 - name: Bob age: 30
Data Types
| Type | Example | Description |
|---|---|---|
| String | name: "Alice" |
Quotes optional (unless special chars) |
| Integer | age: 25 |
Whole numbers |
| Float | pi: 3.14159 |
Decimal numbers |
| Boolean | active: true |
true/false, yes/no, on/off |
| Null | value: null |
null, ~, or empty |
| Date | date: 2024-01-15 |
ISO 8601 format |
| Timestamp | timestamp: 2024-01-15T10:30:00Z |
ISO 8601 with time |
String Variations
# Unquoted (simple strings) name: Alice city: New York # Double quotes (escape sequences) message: "Hello, World!\nWelcome to YAML" # Single quotes (literal) message: 'Hello, World!\nThis is literal' # Multi‑line strings (preserve newlines) description: | This is a multi‑line string. It preserves newlines and indentation. Each line is separated by a newline. # Multi‑line strings (fold newlines → spaces) description: > This is a folded string. Newlines are converted to spaces. This becomes a single line.
Collections
Mappings (Dictionaries / Objects)
# Block style (preferred) person: name: Alice age: 25 address: street: 123 Main St city: New York # Inline style (flow style) person: { name: Alice, age: 25, address: { street: 123 Main St, city: New York } }
Sequences (Lists / Arrays)
# Block style (preferred) fruits: - apple - banana - orange # Inline style (flow style) fruits: [apple, banana, orange] # List of objects people: - name: Alice age: 25 - name: Bob age: 30 # Nested lists matrix: - [1, 2, 3] - [4, 5, 6] - [7, 8, 9]
Anchors & Aliases (Reuse)
# Define anchor (&) defaults: &defaults timeout: 30 retries: 3 # Reference anchor (*) job1: <<: *defaults name: Job 1 job2: <<: *defaults name: Job 2 # Override specific fields job3: <<: *defaults name: Job 3 timeout: 60 # override default # Multi‑level anchors base: &base name: base config: log_level: info extended: &extended <<: *base version: 2.0
Explicit Data Types
# Use !! to specify type int_value: !!int 42 float_value: !!float 3.14 bool_value: !!bool true str_value: !!str 12345 null_value: !!null ~ # Binary data (Base64) data: !!binary c29tZSBkYXRhIGhlcmU= # Timestamp timestamp: !!timestamp 2024-01-15T10:30:00Z # Set (unique values) set: !!set ? apple ? banana ? orange
Multi‑Document YAML
# Multiple documents in one file # Use --- to separate documents --- # first document name: Alice age: 25 --- # second document name: Bob age: 30 --- # third document fruits: - apple - banana # ... (--- at the end is optional)
Common Use Cases
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: default
labels:
app: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: nginx:latest
ports:
- containerPort: 80
env:
- name: ENV
value: production
resources:
requests:
memory: 64Mi
cpu: 250m
limits:
memory: 128Mi
cpu: 500m
Docker Compose
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
volumes:
- ./data:/app/data
depends_on:
- db
- redis
db:
image: postgres:15
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
volumes:
postgres_data:
Helm values.yaml
replicaCount: 3
image:
repository: my-app
tag: latest
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
ingress:
enabled: true
hostname: myapp.example.com
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
config:
logLevel: info
database:
host: postgres
port: 5432
name: myapp
Ansible Playbook
---
- name: Deploy web application
hosts: webservers
become: yes
vars:
app_name: myapp
app_port: 3000
tasks:
- name: Install dependencies
apt:
name: "{{ item }}"
state: present
loop:
- git
- python3
- nginx
- name: Clone repository
git:
repo: https://github.com/user/myapp.git
dest: /var/www/{{ app_name }}
version: main
- name: Start application
systemd:
name: "{{ app_name }}"
state: started
enabled: yes
GitLab CI/CD
stages:
- build
- test
- deploy
variables:
DOCKER_IMAGE: registry.gitlab.com/my-user/my-app
DEPLOY_ENV: production
build:
stage: build
script:
- docker build -t $DOCKER_IMAGE:$CI_COMMIT_SHA .
- docker push $DOCKER_IMAGE:$CI_COMMIT_SHA
test:
stage: test
script:
- docker run $DOCKER_IMAGE:$CI_COMMIT_SHA npm test
deploy:
stage: deploy
script:
- kubectl set image deployment/my-app app=$DOCKER_IMAGE:$CI_COMMIT_SHA
- kubectl rollout status deployment/my-app
only:
- main
Terraform Variables
variable "region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "tags" {
description = "Resource tags"
type = map(string)
default = {
Environment = "production"
Terraform = "true"
}
}
variable "enabled" {
type = bool
default = true
}
Prometheus Alert Rules
groups:
- name: instance
rules:
- alert: InstanceDown
expr: up == 0
for: 5m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} down"
description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes."
- alert: HighCPUUsage
expr: (100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)) > 80
for: 10m
labels:
severity: warning
annotations:
summary: "High CPU usage on {{ $labels.instance }}"
description: "CPU usage is above 80% for more than 10 minutes."
Common Pitfalls & Tips
Common Issues
- Tabs vs spaces – tabs are not allowed (use spaces)
- Inconsistent indentation – must be consistent
- Missing space after colon –
key:valueis invalid - Quotes for special characters –
@, #, :, {, }, [, ] - Booleans –
on,off,yes,noare also valid
Best Practices
- Use 2 spaces for indentation (common standard)
- Use quotes for strings with special characters
- Use block style for readability (not inline)
- Use anchors to avoid repetition
- Use comments to document complex structures
- Validate YAML with tools like
yamllintandyq
Validation Tools
# yamllint – linting yamllint -s file.yaml # yq – YAML processor (like jq) yq eval '.person.name' file.yaml yq eval -i '.person.age = 30' file.yaml # Online validator # https://www.yamllint.com/ # https://jsonformatter.org/yaml-validator
📌 Quick Reference
Key‑value:
Lists:
Indentation: 2 spaces (consistent)
Comments:
Multi‑line:
Anchors:
Documents:
Types: strings (optional quotes), integers, floats, booleans (true/false), null
Tools: yamllint, yq, online validators
key: value (space after colon)Lists:
- item (hyphen + space)Indentation: 2 spaces (consistent)
Comments:
# commentMulti‑line:
| (preserve), > (fold)Anchors:
&anchor and *anchor for reuseDocuments:
--- to separate documentsTypes: strings (optional quotes), integers, floats, booleans (true/false), null
Tools: yamllint, yq, online validators