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:
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}