TExcelTAD

JSON Schema Checks

yamllint checks that a file is well-written YAML. It cannot know that replicas must be a number, that image.tag is required, or that envirnoment is a typo. JSON Schema describes the expected shape of a document (types, required keys, allowed values, patterns), and a validator checks a file against it. Despite the name, it works for YAML just as well, because YAML and JSON share the same data model. Kubernetes, Helm (values.schema.json), GitHub Actions, Compose and most CI systems publish schemas, and your own tools should too.

The JSON course introduces the schema language; this lesson uses it to guard configuration.

A schema for a service config

Here is a schema for a small deployment config, and a validator run on three files. The examples use Python's jsonschema package (4.23, in the browser) with PyYAML to read the YAML:

python · try it yourself
import yaml
from jsonschema import Draft202012Validator

schema = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "required": ["service", "image", "replicas"],
    "additionalProperties": False,
    "properties": {
        "service":  {"type": "string", "pattern": "^[a-z][a-z0-9-]{1,40}
quot;}, "image": { "type": "object", "required": ["repository", "tag"], "properties": { "repository": {"type": "string"}, "tag": {"type": "string", "minLength": 1}, }, }, "replicas": {"type": "integer", "minimum": 1, "maximum": 20}, "environment": {"enum": ["dev", "staging", "prod"]}, }, } files = { "good.yaml": """ service: shop-api image: {repository: registry.example.com/shop-api, tag: "1.4.2"} replicas: 3 environment: prod """, "typos.yaml": """ service: Shop_API image: {repository: registry.example.com/shop-api, tag: 1.10} replicas: "3" envirnoment: prod """, "missing.yaml": """ service: shop-api replicas: 0 """, } validator = Draft202012Validator(schema) for name, text in files.items(): doc = yaml.safe_load(text) errors = sorted(validator.iter_errors(doc), key=lambda e: list(e.path)) print(f"{name}: {'OK' if not errors else f'{len(errors)} error(s)'}") for e in errors: where = "/".join(str(p) for p in e.path) or "(root)" print(f" {where}: {e.message}")
good.yaml: OK
typos.yaml: 4 error(s)
  (root): Additional properties are not allowed ('envirnoment' was unexpected)
  image/tag: 1.1 is not of type 'string'
  replicas: '3' is not of type 'integer'
  service: 'Shop_API' does not match '^[a-z][a-z0-9-]{1,40}
  


missing.yaml: 2 error(s)
  (root): 'image' is a required property
  replicas: 0 is less than the minimum of 1

Every error names the path and the problem, which is what makes schema checks pleasant in CI. Note what the schema caught that no YAML tool could:

  • tag: 1.10 parsed as a number (the float 1.1), not the string the schema requires: the YAML gotcha turned into a clear error.
  • replicas: "3" is a string; a program doing arithmetic with it would fail much later.
  • "additionalProperties": false turns the typo envirnoment into an error instead of a silently ignored key.

Making your own tool validate its config

A script or CLI that reads a config file should validate it before doing anything, and fail with exit status 2 (a usage error) and readable messages. Wrapping the validator in a function keeps that one call:

python · try it yourself
import yaml
from jsonschema import Draft202012Validator

SCHEMA = {
    "type": "object",
    "required": ["targets"],
    "properties": {
        "timeout_seconds": {"type": "number", "exclusiveMinimum": 0, "default": 5},
        "targets": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "required": ["name", "url"],
                "properties": {
                    "name": {"type": "string"},
                    "url": {"type": "string", "pattern": "^https?://"},
                    "expect_status": {"type": "integer", "default": 200},
                },
                "additionalProperties": False,
            },
        },
    },
    "additionalProperties": False,
}

def load_config(text):
    """Return (config, errors). Defaults from the schema are filled in for valid configs."""
    doc = yaml.safe_load(text)
    errors = [f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}"
              for e in Draft202012Validator(SCHEMA).iter_errors(doc)]
    if errors:
        return None, errors
    doc.setdefault("timeout_seconds", SCHEMA["properties"]["timeout_seconds"]["default"])
    for t in doc["targets"]:
        t.setdefault("expect_status", 200)
    return doc, []

def main(text):
    config, errors = load_config(text)
    if errors:
        for line in errors:
            print("config error:", line)
        return 2
    for t in config["targets"]:
        print(f"would check {t['name']} at {t['url']} (expect {t['expect_status']}, timeout {config['timeout_seconds']}s)")
    return 0

print("exit", main("targets:\n  - {name: api, url: https://api.example.com/healthz}\n  - {name: web, url: https://www.example.com/, expect_status: 301}\n"))
print("exit", main("targets:\n  - {name: api, url: api.example.com/healthz, retries: 3}\n"))
would check api at https://api.example.com/healthz (expect 200, timeout 5s)
would check web at https://www.example.com/ (expect 301, timeout 5s)
exit 0
config error: targets/0/url: 'api.example.com/healthz' does not match '^https?://'
config error: targets/0: Additional properties are not allowed ('retries' was unexpected)
exit 2

JSON Schema validation does not apply default values by itself; the code fills them in after validation, so the rest of the program can rely on every key being present.

The same check from the shell

In CI you usually do not write Python for this. check-jsonschema (a Python CLI built on the same library) validates YAML, JSON and TOML files against a local schema, a URL, or one of the schemas it ships for common formats:

bash
pipx install check-jsonschema          # or: uv tool install check-jsonschema

check-jsonschema --schemafile schema.json deploy/*.yaml
check-jsonschema --builtin-schema vendor.github-workflows .github/workflows/*.yml
check-jsonschema --builtin-schema vendor.gitlab-ci .gitlab-ci.yml
text
Schema validation errors were encountered.
  deploy/typos.yaml::$.replicas: '3' is not of type 'integer'

For Kubernetes manifests, use kubeconform, which knows the schema of every built-in resource for a given Kubernetes version; it is covered in Kubernetes Packaging: Helm & Kustomize. Editors can use schemas too: a first-line comment # yaml-language-server: $schema=./schema.json gives autocompletion and inline errors in VS Code's YAML extension.

Test yourself

What can a JSON Schema check catch that yamllint cannot?

  1. Tabs in indentation
  2. Trailing spaces
  3. A required key that is missing, or a value of the wrong type
  4. Duplicate keys

What does "additionalProperties": false do?

  1. Makes all properties optional
  2. Rejects keys that the schema does not list, so typos become errors
  3. Allows any extra keys
  4. Disables validation of nested objects

Why does the schema reject tag: 1.10?

  1. Tags cannot contain dots
  2. YAML parses 1.10 as a number, and the schema requires a string
  3. The tag is too long
  4. 1.10 is not a valid version