YAML Best Practices

Writing valid YAML is just the first step. Writing good YAML means creating files that are readable, maintainable, consistent, and safe. These best practices come from real-world experience with DevOps tools, open-source projects, and enterprise configuration management. Following these guidelines produces YAML files that are easy to understand and less likely to cause bugs.

1. Use 2-Space Indentation Consistently

The YAML community standard is 2 spaces per indentation level. Some tools use 4 spaces. Either works, but pick one and stick with it throughout the entire file. Never mix them.

Good

server:
  host: localhost
  database:
    name: mydb
    port: 5432

Bad (Mixing 2 and 4 spaces)

server:
  host: localhost
    database:         ← 4 spaces used here — inconsistent
        name: mydb    ← 8 spaces — hard to follow

Tip: Configure the editor to use 2 spaces and show whitespace characters. This catches inconsistencies instantly.

2. Always Use Lowercase for Keys

Use lowercase letters and underscores for all key names. Avoid camelCase and mixed case. This follows the convention used in most tools (Kubernetes, Ansible, Docker) and prevents confusion from YAML's case-sensitive nature.

# Good
database_host: localhost
max_retries: 3

# Avoid
DatabaseHost: localhost
MaxRetries: 3

3. Quote Strings with Special Characters

Any value containing a colon, hash, bracket, ampersand, asterisk, or exclamation mark must be quoted. When in doubt, quoting a value is always safe.

# Always quote these kinds of values
error_message: "Error: connection refused"
api_url: "https://api.example.com/v1"
color_hex: "#FF5733"
regex_pattern: "^[a-z]+$"

4. Be Explicit with Boolean Values

Use only true and false for boolean values. Avoid yes, no, on, and off. These alternatives are valid in YAML 1.1 but cause problems when different parsers handle them differently.

# Good
debug: false
ssl_enabled: true

# Avoid
debug: no
ssl_enabled: yes

5. Add Comments for Non-Obvious Values

Comment every value that is not self-explanatory. Explain units, expected ranges, or the reason for a specific value. Comments cost nothing and save time for anyone maintaining the file later.

server:
  port: 8443          # HTTPS port (standard is 443 for production)
  timeout: 30         # Seconds — increase for slow connections
  max_connections: 100  # Reduce to 50 on low-memory servers
  debug: false        # Set to true only in local development

6. Use Anchors to Avoid Repeating Common Settings

When the same block of settings appears in multiple places, define it once with an anchor and reference it with aliases. This keeps the file DRY (Don't Repeat Yourself) and makes updates easier.

# Define once
common: &common
  image: nginx:1.25
  restart: always
  logging:
    driver: json-file

# Reuse twice
web:
  <<: *common
  ports:
    - "80:80"

api:
  <<: *common
  ports:
    - "3000:3000"

7. Group Related Settings with Meaningful Parent Keys

Flat configurations with dozens of keys at the top level become hard to navigate. Group related settings under descriptive parent keys.

Less Organized

db_host: localhost
db_port: 5432
db_name: mydb
log_level: info
log_format: json
cache_host: redis
cache_port: 6379

Well Organized

database:
  host: localhost
  port: 5432
  name: mydb

logging:
  level: info
  format: json

cache:
  host: redis
  port: 6379

8. Store Secrets Outside YAML Files

Never hardcode passwords, API keys, or tokens directly in YAML files. These files often end up in version control systems like Git, which makes sensitive values visible to anyone with repository access.

# Bad – never do this
database:
  password: mySecretPassword123

# Good – reference an environment variable
database:
  password: ${DB_PASSWORD}    # Loaded at runtime from env var

Use environment variables, secret management tools (Vault, AWS Secrets Manager), or Kubernetes Secrets to manage sensitive values.

9. Validate YAML Files Before Deployment

Always validate YAML before applying it to production systems. Use a linter or dry-run option to catch errors early.

# Check YAML syntax with yamllint
yamllint config.yaml

# Test Kubernetes YAML without applying
kubectl apply -f deployment.yaml --dry-run=client

# Validate Docker Compose file
docker compose config

10. Use Explicit Null Values

When a key intentionally has no value, write null explicitly rather than leaving it empty. Explicit null is clearer in intent.

# Good – intent is clear
middle_name: null
backup_email: null

# Less clear – empty value could be accidental
middle_name:
backup_email:

11. Use the Document Separator for Multi-Resource Files

When a single YAML file contains multiple documents or Kubernetes resources, separate each with ---. Add a comment above each resource to identify it quickly.

# Deployment
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
spec:
  replicas: 3
  ...

# Service
---
apiVersion: v1
kind: Service
metadata:
  name: web-service
spec:
  ...

12. Keep Lines Reasonably Short

Long lines in YAML are hard to read. For long string values, use folded blocks (>) or literal blocks (|) to split the content across multiple readable lines.

# Instead of one very long line:
description: "This is a very long description that goes on and on and becomes hard to read in a normal editor window."

# Use folded block:
description: >
  This is a long description that is split
  across multiple lines for readability.
  YAML folds it into one paragraph automatically.

Best Practices Summary Table

#PracticeWhy It Matters
1Use 2-space indentation consistentlyPrevents parse errors and improves readability
2Use lowercase keys with underscoresConsistent, avoids case-sensitivity bugs
3Quote strings with special charactersPrevents misinterpretation by the parser
4Use only true/false for booleansWorks reliably across all YAML versions
5Comment non-obvious valuesHelps future maintainers understand the file
6Use anchors to avoid repetitionDRY principle — one change updates everywhere
7Group related settingsEasier to navigate large configuration files
8Never hardcode secretsPrevents security vulnerabilities
9Validate before deployingCatches syntax errors before they cause outages
10Use explicit null valuesMakes intent clear, avoids confusion
11Use --- for multi-document filesPrevents documents from merging incorrectly
12Keep lines short and readableImproves editor experience and code reviews

Summary

  • Consistent 2-space indentation and lowercase keys form the foundation of clean YAML
  • Quote any string value that contains YAML special characters
  • Use anchors and aliases to eliminate repeated configuration blocks
  • Keep secrets out of YAML files — use environment variables or secret management tools
  • Always validate YAML files before applying them to live systems
  • Comment important settings and group related keys under meaningful parent keys
  • Following these practices reduces errors, improves readability, and makes configuration files easier to maintain long-term

Leave a Comment