Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scott2b/d4fe361b8b717c9a35dade904fdb6640 to your computer and use it in GitHub Desktop.
Save scott2b/d4fe361b8b717c9a35dade904fdb6640 to your computer and use it in GitHub Desktop.
import os
import re
class ConfigurationError(Exception): pass
def replacer(m):
var = m.group(2)[2:-1].strip()
try:
return f'{m.group(1)}{os.environ[var]}{m.group(3)}'
except KeyError:
if var:
msg = f'Environment variable {var} is not set.'
else:
msg = f'Empty environment variable construction in configuration.'
raise EnvironmentError(msg)
envvar_pat = re.compile(r'(.*?)(\${.*?})(.*?)')
def envvar_constructor(loader, node):
var = loader.construct_scalar(node)
try:
return envvar_pat.sub(replacer, var)
except EnvironmentError as e:
raise ConfigurationError(
f'\n{node.start_mark}\n{node.end_mark}\n' +
str(e)
)
yaml.add_implicit_resolver ("!env_var", envvar_pat)
yaml.add_constructor('!env_var', envvar_constructor)
def load_config(configfile):
with open(configfile) as f:
return yaml.load(f.read(), Loader=yaml.FullLoader)
@scott2b
Copy link
Author

scott2b commented Jul 10, 2020

Parses Yaml files with ${} templated variables interpreted as environment variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment