Pyaml-env: YAML with Environment Variable Resolution

1.2.2 · active · verified Thu Apr 16

Pyaml-env provides a straightforward way to parse YAML configuration files, automatically resolving environment variables denoted by the `!ENV` tag. It's built on top of PyYAML and is currently at version 1.2.2. The library maintains an active release cadence, with updates typically addressing bug fixes, dependency compatibility, and feature enhancements a few times a year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a YAML configuration file with embedded `!ENV` tags. It shows how environment variables are resolved and how to provide default values using a colon (`:`) separator. It also illustrates accessing the parsed configuration and cleans up after execution.

import os
from pyaml_env import parse_config

# Simulate setting environment variables
os.environ['API_KEY'] = 'your_secret_api_key'
os.environ['DEBUG_MODE'] = 'true'
os.environ['DB_PORT'] = '5432'

# Create a dummy YAML file for demonstration
config_content = """
api_config:
  key: !ENV API_KEY
  endpoint: https://api.example.com/v1
debug:
  enabled: !ENV DEBUG_MODE:false # 'false' is default if DEBUG_MODE is not set
database:
  host: localhost
  port: !ENV DB_PORT:3306 # '3306' is default if DB_PORT is not set
  user: !ENV DB_USER:default_user # 'default_user' is default if DB_USER is not set
logging:
  level: INFO
"""
with open('config.yaml', 'w') as f:
    f.write(config_content)

# Parse the configuration file
config = parse_config('config.yaml')

# Access resolved configuration values
print(f"API Key: {config['api_config']['key']}")
print(f"Debug Enabled: {config['debug']['enabled']} (type: {type(config['debug']['enabled'])})")
print(f"Database Port: {config['database']['port']} (type: {type(config['database']['port'])})")
print(f"Database User: {config['database']['user']}")

# Clean up the dummy file and environment variables
os.remove('config.yaml')
del os.environ['API_KEY']
del os.environ['DEBUG_MODE']
del os.environ['DB_PORT']
if 'DB_USER' in os.environ: # Only delete if it was actually set by this script or existed before
    del os.environ['DB_USER']

view raw JSON →