Created
April 7, 2018 03:19
-
-
Save VillanCh/1486316511df7b765c0bc9768905b089 to your computer and use it in GitHub Desktop.
Using PyYaml load env vars
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
# | |
# load yaml by env variables | |
# | |
import yaml, os, re | |
pattern = re.compile( '^\$\{(.*?)(:(.*))?\}$' ) | |
yaml.add_implicit_resolver ( "!env", pattern ) | |
def env_construction(loader, node): | |
value = loader.construct_scalar(node) | |
env_var_name, _, default = pattern.match(value).groups() | |
env_var = os.getenv(env_var_name, default) | |
if not env_var: | |
raise ValueError('the environment variable: {} is not existed.'.format(env_var_name)) | |
return env_var | |
yaml.add_constructor('!env', env_construction) | |
pattern2 = re.compile('^\$(.*?)(:(.*))?$') | |
yaml.add_implicit_resolver('!env2', pattern2) | |
def env2_construction(loader, node): | |
value = loader.construct_scalar(node) | |
env_var_name, _, default = pattern2.match(value).groups() | |
env_var = os.getenv(env_var_name, default) | |
if not env_var: | |
raise ValueError('the environment variable: {} is not existed.'.format(env_var_name)) | |
return env_var | |
yaml.add_constructor('!env2', env2_construction) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment