infrastructure/visualize.py

100 lines
2.7 KiB
Python
Raw Normal View History

2024-10-14 15:49:44 +00:00
#!/usr/bin/env python
import json
import sys
2024-10-14 20:11:20 +00:00
import jinja2
import hcl2
2024-10-14 20:11:20 +00:00
2024-10-14 15:49:44 +00:00
icon_overrides = {
"acme_dns": "lets-encrypt",
"extra_services": None,
"faas": None,
"forgejo_runner": "forgejo",
"healthcheck": "healthchecks",
"mailcowdockerized": "mailcow",
"reitanlage_oranienburg": "grav",
"tandoor": "tandoor-recipes",
"teamspeak_fallback": None,
"tinytinyrss": "tiny-tiny-rss",
"wiki_js": "wiki-js",
"woodpecker": None,
}
2024-10-14 18:53:13 +00:00
icon_format = {
"linkwarden": "webp",
"telegraf": "webp",
"tiny-tiny-rss": "webp",
}
def get_icon(svc):
svc = icon_overrides.get(svc, svc) or 'docker'
fmt = icon_format.get(svc, 'svg')
return f'https://cdn.jsdelivr.net/gh/selfhst/icons/{fmt}/{svc}.{fmt}'
def host_key(host, hosts):
return f"'serguzim.net'.{hosts[host]["provider"]}.{host}"
def service_key(svc, data, hosts):
return f"{host_key(data["host"], hosts)}.{svc}"
2024-10-14 20:11:20 +00:00
2024-10-14 15:49:44 +00:00
def service_key_find(svc_name, services, hosts):
if svc := services.get(svc_name):
return service_key(svc_name, svc, hosts)
2024-10-14 15:49:44 +00:00
return None
def parse_hosts(hosts):
result = []
2024-10-14 20:11:20 +00:00
for host, data in hosts.items():
result.append({
'key': host_key(host, hosts),
2024-10-14 20:11:20 +00:00
'name': host,
})
2024-10-14 15:49:44 +00:00
return result
def parse_services(services, hosts):
2024-10-14 15:49:44 +00:00
result = []
postgresql_key = service_key_find("postgresql", services, hosts)
authentik_key = service_key_find("authentik", services, hosts)
2024-10-14 15:49:44 +00:00
for svc, data in services.items():
svc_key = service_key(svc, data, hosts)
2024-10-14 15:49:44 +00:00
domains = []
2024-10-14 20:11:20 +00:00
for dns in data.get("dns") or []:
domains.append(f"- {dns['domain']}")
2024-10-14 20:11:20 +00:00
data['key'] = svc_key
data['label'] = "\\n".join([svc] + domains)
data['icon'] = get_icon(svc)
result.append(data)
2024-10-14 15:49:44 +00:00
return result
if __name__ == '__main__':
hosts = {}
services = {}
2024-10-14 20:11:20 +00:00
with open('./hosts.auto.tfvars', 'r') as file:
hosts = hcl2.load(file)["hosts"][0]
with open('./services.auto.tfvars', 'r') as file:
services = hcl2.load(file)["services"][0]
db_key = service_key_find("postgresql", services, hosts)
auth_key = service_key_find("authentik", services, hosts)
monitoring_key = service_key_find("gatus", services, hosts)
2024-10-14 20:11:20 +00:00
jinja_loader = jinja2.FileSystemLoader(searchpath="./templates")
jinja_env = jinja2.Environment(loader=jinja_loader)
template = jinja_env.get_template("infrastructure.d2.j2")
print(template.render(
2024-10-14 20:11:20 +00:00
grid_svcs=[db_key, auth_key],
svcs=parse_services(services, hosts),
hosts=parse_hosts(hosts),
2024-10-14 20:11:20 +00:00
db_key=db_key,
auth_key=auth_key,
monitoring_key=monitoring_key,
))