def parse_config(config_path):
"""Checks if secrets need to be fetched from the environment"""
temp_path = "%s.tmp" % config_path
# Template yaml file
with open(config_path, 'r') as stream:
try:
temp = template_yaml(yaml.load(stream))
except yaml.YAMLError as exc:
raise ValueError("Invalid config passed to the program: %s" % exc)
# Dump templated file back to file-system
with open(temp_path, 'w') as outfile:
yaml.safe_dump(temp, outfile, default_flow_style=False)
# Add environment resolver
pattern_env = re.compile(r'^(.*)\<%= ENV\[\'(.*)\'\] %\>(.*)$')
yaml.add_implicit_resolver("!pathex", pattern_env)
# Add command resolver
pattern_cmd = re.compile(r'^(.*)\<%= CMD\[\'(.*)\'\] %\>(.*)$')
yaml.add_implicit_resolver("!pathcmd", pattern_cmd)
# Add function resolver
pattern_fun = re.compile(r'^(.*)\<%= FUNC\[\'(.*)\((.*)\)\'\] %\>(.*)$')
yaml.add_implicit_resolver("!func", pattern_fun)
def pathex_constructor(loader, node):
"""Processes environment variables found in the YAML"""
value = loader.construct_scalar(node)
before_path, env_var, remaining_path = pattern_env.match(value).groups()
return before_path + os.environ[env_var] + remaining_path
def pathcmd_constructor(loader, node):
"""Processes command variables found in the YAML"""
value = loader.construct_scalar(node)
before_path, cmd_var, remaining_path = pattern_cmd.match(value).groups()
retval = output_value(execute(cmd_var, None, True, True), True)
return before_path + retval.decode("utf-8") + remaining_path
def fun_constructor(loader, node):
"""Processes embedded functions found in the YAML"""
value = loader.construct_scalar(node)
before_path, fun, arg, remaining_path = pattern_fun.match(value).groups()
retval = PREDEFINED_FUNCTIONS[fun](arg)
return before_path + retval.decode("utf-8") + remaining_path
yaml.add_constructor("!pathex", pathex_constructor)
yaml.add_constructor("!pathcmd", pathcmd_constructor)
yaml.add_constructor("!func", fun_constructor)
with open(temp_path, 'r') as stream:
try:
return yaml.load(stream)
except yaml.YAMLError as exc:
raise ValueError("Invalid config passed to the program: %s" % exc)
评论列表
文章目录