I am currently building a python application that uses YAML configs. I generate the YAML config file by using other YAML files. I have a "template" YAML, which defines the basic structure I want in the YAML file the app uses, and then many different "data" YAMLs that fill in the template to spin the application's behavior a certain way. So for example say I had 10 "data" YAMLs. Depending on where the app is being deployed, 1 "data" YAML is chosen, and used to fill out the "template" YAML. The resulting filled out YAML is what the application uses to run. This saves me a ton of work. I have run into a problem with this method though. Say I have a template YAML that looks like this:
id: {{id}}
endpoints:
url1: https://website.com/{{id}}/search
url2: https://website.com/foo/{{id}}/get_thing
url3: https://website.com/hello/world/{{id}}/trigger_stuff
foo:
bar:
deeply:
nested: {{id}}
Then somewhere else, I have like 10 "data" YAMLs each with a different value for {{id}}. I cant seem to figure out an efficient way to replace all these {{id}} occurrences in the template. I am having a problem because sometimes the value to be substituted is a substring of a value I want to mostly keep, or the occurrences are very far apart from each other in the hierarchy, making looping solutions inefficient. My current method for generating the config file using template+data looks something like this in python:
import yaml
import os
template_yaml = os.path.abspath(os.path.join(os.path.dirname(__file__), 'template.yaml'))
# In this same folder you would find flavor2, flavor3, flavor4, etc, lets just use 1 for now
data_yaml = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data_files', 'flavor1.yaml'))
# This is where we dump the filled out template the app will actually use
output_directory = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
with open(template_yaml, 'r') as template:
try:
loaded_template = yaml.load(template) # Load the template as a dict
with open(data_yaml , 'r') as data:
loaded_data= yaml.load(data) # Load the data as a dict
# From this point on I am basically just setting individual keys from "loaded_template" to values in "loaded_data"
# But 1 at a time, which is what I am trying to avoid:
loaded_template['id'] = loaded_data['id']
loaded_template['endpoints']['url1'] = loaded_template['endpoints']['url1'].format(loaded_data['id'])
loaded_template['foo']['bar']['deeply']['nested'] = loaded_data['id']
Any idea on how to go through and change all the {{id}} occurrences faster?