Linting and schema validation

YAML · Advanced · 10 min

Config errors found by a linter in seconds would otherwise surface as failed deploys.

Two kinds of checks catch most YAML problems.

Linting checks syntax and style. yamllint reports indentation inconsistencies, duplicate keys, trailing spaces, overly long lines, truthy values like yes and on that should be quoted or written as true, and missing document starts. Configure rules in .yamllint; the relaxed preset is a gentle start.

Schema validation checks structure and types: required keys, allowed values, number ranges, string patterns. The common approach is JSON Schema, applied to the loaded data, since YAML and JSON share a data model.

  • Editors: the YAML language server (VS Code's Red Hat YAML extension) validates and autocompletes against schemas, picking them from the SchemaStore catalog by filename (GitHub workflows, Compose files, many others) or from a # yaml-language-server: $schema=... comment at the top of the file.
  • CI: check-jsonschema validates files on the command line; kubeconform validates Kubernetes manifests; actionlint checks GitHub Actions workflows.
  • In code: load with a safe loader, then validate with a JSON Schema library or a typed model (Pydantic, for example).

Duplicate keys deserve special mention: many parsers silently keep the last value, so a duplicated image: deep in a manifest goes unnoticed. yamllint's key-duplicates rule catches it.

Example

# .yamllint
extends: default
rules:
  line-length: {max: 120}
  truthy: {allowed-values: ["true", "false"]}
  document-start: disable

# app.yaml
# yaml-language-server: $schema=./app.schema.json
name: web
replicas: two          # schema error: should be an integer
debug: yes             # yamllint: truthy value should be one of [true, false]
name: api              # yamllint: duplication of key "name" in mapping

# $ yamllint app.yaml
#   4:8   warning  truthy value should be one of [false, true]  (truthy)
#   5:1   error    duplication of key "name" in mapping  (key-duplicates)
# $ check-jsonschema --schemafile app.schema.json app.yaml   (once the duplicate is fixed)
#   app.yaml::$.replicas: 'two' is not of type 'integer'

Remember

  • yamllint catches syntax, style, truthy values and duplicate keys
  • JSON Schema validates structure and types of the loaded data
  • Editors validate live via SchemaStore or a $schema comment

Watch out for

  • Relying on the parser to report duplicate keys; many keep the last one silently.

Check yourself

  1. A manifest accidentally defines image: twice in one mapping. What do many parsers do?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: yamllint.readthedocs.io/en/stable/

Builds on

Unlocks

Nothing builds on this yet.