EnvYAML
EnvYAML is a Python library that simplifies reading YAML configuration files and seamlessly integrates environment variables. It allows referencing environment variables directly within YAML files using the `${VAR_NAME}` or `$VAR_NAME` syntax, providing a flexible and secure way to manage configurations. The library is currently at version 1.10.211231 and is actively maintained with regular updates, often focusing on bug fixes and minor feature enhancements.
Warnings
- breaking Enabling 'strict' mode (which is default) can cause `ValueError` exceptions if environment variables are not defined. Prior to version 1.5.201226, strict mode might have been less stringent about duplicate variable definitions in `.env` files.
- gotcha Single dollar sign (`$VAR_NAME`) is used for environment variable substitution. To use a literal dollar sign in your YAML, it must be escaped with a double dollar sign (`$$`). For example, `escaped: $$.extra` will result in `$.extra`.
- gotcha Parsing of boolean values can be ambiguous in YAML. Strings like `NO`, `ON`, `OFF`, `YES`, `TRUE`, `FALSE` (case-insensitive) can be interpreted as boolean `False` or `True` respectively by underlying YAML parsers (like PyYAML, which EnvYAML uses).
- deprecated Older versions of EnvYAML might have handled escaped dollar signs or multiple variable definitions differently. Version 1.10.211231 specifically made a 'specific replacement instead of a general replacement for escaped dollar signs', indicating a refinement in how escaping is processed.
Install
-
pip install envyaml
Imports
- EnvYAML
from envyaml import EnvYAML
Quickstart
import os
from envyaml import EnvYAML
# Create a dummy YAML file
with open('config.yaml', 'w') as f:
f.write('app:\n')
f.write(' name: "${APP_NAME}"\n')
f.write(' version: "${APP_VERSION|1.0.0}"\n')
f.write('database:\n')
f.write(' host: $DB_HOST\n')
f.write(' port: $DB_PORT|5432\n')
f.write(' password: $DB_PASSWORD
')
# Set environment variables (or they will default if specified in YAML)
os.environ['APP_NAME'] = 'MyAwesomeApp'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PASSWORD'] = os.environ.get('DB_PASSWORD', 'super_secret_dev')
# Initialize EnvYAML
env = EnvYAML('config.yaml')
# Access configuration values
print(f"App Name: {env['app.name']}")
print(f"App Version: {env['app.version']}")
print(f"Database Host: {env['database.host']}")
print(f"Database Port: {env['database.port']}")
print(f"Database Password: {env['database.password']}")
# Clean up dummy file
os.remove('config.yaml')