Pass config to node renderer

This commit is contained in:
2025-11-11 03:41:59 +01:00
parent 14e88a6734
commit c121533161

View File

@@ -35,12 +35,12 @@ TEMPLATES = Environment(
) )
def render_templates(node: dict): def render_templates(node: dict, args: dict):
class Inner(json.JSONEncoder): class Inner(json.JSONEncoder):
def default(self, o): def default(self, o):
if isinstance(o, Template): if isinstance(o, Template):
try: try:
rendered = o.render(node) rendered = o.render(args | node)
except Exception as e: except Exception as e:
e.add_note(f"While rendering for: {node['hostname']}") e.add_note(f"While rendering for: {node['hostname']}")
raise e raise e
@@ -131,6 +131,11 @@ def walk_files(root: pathlib.Path):
def main(): def main():
with open(ROOT.joinpath("config.yaml")) as fyaml:
config = yaml.safe_load(fyaml)
template_args = {"config": config, "root": ROOT}
nodes = [] nodes = []
for fullname in walk_files(NODES): for fullname in walk_files(NODES):
filename = str(fullname.relative_to(NODES).parent) + "/" + fullname.stem filename = str(fullname.relative_to(NODES).parent) + "/" + fullname.stem
@@ -145,7 +150,10 @@ def main():
# Quick and dirty way to resolve all the templates using a custom encoder # Quick and dirty way to resolve all the templates using a custom encoder
nodes = list( nodes = list(
map( map(
lambda node: json.loads(json.dumps(node, cls=render_templates(node))), nodes lambda node: json.loads(
json.dumps(node, cls=render_templates(node, template_args))
),
nodes,
) )
) )
@@ -155,16 +163,13 @@ def main():
dict(s) for s in set(frozenset(node["cluster"].items()) for node in nodes) dict(s) for s in set(frozenset(node["cluster"].items()) for node in nodes)
] ]
with open(ROOT.joinpath("config.yaml")) as fyaml: template_args |= {"nodes": nodes, "clusters": clusters}
config = yaml.safe_load(fyaml)
RENDERED.mkdir(exist_ok=True) RENDERED.mkdir(exist_ok=True)
for template_name in TEMPLATES.list_templates(): for template_name in TEMPLATES.list_templates():
template = TEMPLATES.get_template(template_name) template = TEMPLATES.get_template(template_name)
rendered = template.render( rendered = template.render(template_args)
nodes=nodes, clusters=clusters, config=config, root=ROOT
)
with open(RENDERED.joinpath(template_name), "w") as f: with open(RENDERED.joinpath(template_name), "w") as f:
f.write(rendered) f.write(rendered)