import yaml import os import re from dotenv import load_dotenv from pyaml_env import parse_config import json load_dotenv() #conf = parse_config('mcpo_config.yaml') #print(conf) # pattern for global vars: look for ${word} pattern = re.compile(r'.*?\${(\w+)}.*?') loader = yaml.SafeLoader tag = '!ENV' # the tag will be used to mark where to start searching for the pattern # e.g. somekey: !ENV somestring${MYENVVAR}blah blah blah loader.add_implicit_resolver(tag, pattern, None) conf=None def constructor_env_variables(loader, node): """ Extracts the environment variable from the node's value :param yaml.Loader loader: the yaml loader :param node: the current node in the yaml :return: the parsed string that contains the value of the environment variable """ value = loader.construct_scalar(node) match = pattern.findall(value) if match: full_value = value for g in match: full_value = full_value.replace( f'${{{g}}}', os.environ.get(g, g) ) return full_value return value loader.add_constructor(tag, constructor_env_variables) with open('mcpo_config.yaml') as yaml_conf: try: conf = yaml.load(yaml_conf, Loader=loader) except yaml.YAMLError as exc: print(exc) with open("config.json", "w") as json_file: json.dump(conf, json_file, indent=2)