40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
"""Render phil/ansible's Caddyfile.j2 for `caddy validate`.
|
|
|
|
Usage: render_caddyfile.py <ansible checkout> (prints the Caddyfile)
|
|
Only non-secret group_vars are loaded. Values that reference other variables
|
|
are resolved by rendering until nothing changes; values that need the vault
|
|
stay unresolved, and StrictUndefined makes the Caddyfile fail loudly if it
|
|
ever uses one.
|
|
"""
|
|
import pathlib, sys
|
|
import jinja2, yaml
|
|
|
|
root = pathlib.Path(sys.argv[1])
|
|
ctx = {}
|
|
for f in ("domains.yml", "infrastructure.yml"):
|
|
ctx.update(yaml.safe_load((root / "group_vars/all" / f).read_text()) or {})
|
|
ctx["caddy_custom"] = True
|
|
|
|
env = jinja2.Environment(undefined=jinja2.StrictUndefined, keep_trailing_newline=True)
|
|
|
|
def resolve(o):
|
|
if isinstance(o, dict):
|
|
return {k: resolve(v) for k, v in o.items()}
|
|
if isinstance(o, list):
|
|
return [resolve(v) for v in o]
|
|
if isinstance(o, str) and "{{" in o:
|
|
try:
|
|
return env.from_string(o).render(ctx)
|
|
except jinja2.UndefinedError:
|
|
return o
|
|
return o
|
|
|
|
for _ in range(10):
|
|
new = resolve(ctx)
|
|
if new == ctx:
|
|
break
|
|
ctx = new
|
|
|
|
tmpl = (root / "roles/docker/templates/Caddyfile.j2").read_text()
|
|
sys.stdout.write(env.from_string(tmpl).render(ctx))
|