Last active
July 10, 2020 20:07
-
-
Save scott2b/d4fe361b8b717c9a35dade904fdb6640 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parses Yaml files with ${} templated variables interpreted as environment variables.