A Python utility for validating user YAML configuration files against a default/template YAML file with support for optional fields.
- Validates that required keys from a default YAML are present in a user YAML
- Supports marking keys as optional using
#optional
comments - Type checking between user and default configurations
- Recursive validation for nested YAML structures
- Clear error messages indicating missing keys or type mismatches
pip install -r requirements.txt
./yaml_validator.py <user_config.yaml> <default_config.yaml>
user_config.yaml
: The YAML file to validatedefault_config.yaml
: The template/default YAML file with annotations
0
: Validation successful1
: Validation failed (missing required keys or type mismatches)
from yaml_validator import validate_config
# Validate a user config against a default template
is_valid = validate_config('user_config.yaml', 'default_config.yaml')
if is_valid:
print("Configuration is valid!")
else:
print("Configuration validation failed.")
# Handle the error appropriately
The validate_config
function returns True
if validation passes, False
otherwise. Validation errors are printed to stdout.
In your default YAML file, mark optional keys with #optional
:
database:
host: localhost
port: 5432
username: admin
password: secret #optional
ssl_enabled: true #optional
Keys without #optional
are treated as required.
- Required Keys: Keys in the default file without
#optional
must exist in the user file - Type Matching: When a key exists in both files, the value types must match
- Nested Validation: Nested dictionaries are validated recursively
- Optional Keys: Keys marked with
#optional
can be omitted from the user file
default.yaml:
app:
name: MyApp
version: 1.0
debug: false #optional
database:
host: localhost
port: 5432
user.yaml:
app:
name: MyApp
version: 1.0
database:
host: db.example.com
port: 5432
Running the validator:
./yaml_validator.py user.yaml default.yaml
# Exit code 0 - validation passes
- Annotation Extraction (
extract_annotations
): Parses the default YAML file to identify which keys are optional or required based on#optional
comments - Recursive Validation (
validate_config_recursive
): Traverses both YAML structures simultaneously, checking for missing keys and type mismatches - Error Reporting: Prints detailed messages for each validation failure with the full key path