railiance-infra/ansible/inventory_from_yaml.py
codex 4d9e77c968
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s
Close RAIL-HO-WP-0009 declared-state gaps; leave live 6443 prune gated
Make the k3s API tunnel-only (ADR-005), stop declaring Flannel VXLAN
open to Anywhere, tag the base role so firewall can be scoped, and
schedule the Goss declared-vs-live check. CoulombCore sets ufw_manage
false so a converge cannot enable UFW there. T02 still needs operator
approval for make converge-firewall HOST=Railiance01.
2026-08-15 15:41:59 +02:00

64 lines
2.2 KiB
Python
Executable file

#!/usr/bin/env python3
import json, yaml, subprocess, os, sys, pathlib, glob
def load_servers():
with open(os.path.join(os.path.dirname(__file__), '..', 'inventory', 'servers.yaml')) as f:
data = yaml.safe_load(f)
servers = data.get('servers', [])
return servers
def load_tf_outputs():
# Try to read terraform outputs to attach IPs, if available.
try:
out = subprocess.check_output(['terraform', '-chdir=../terraform/hetzner', 'output', '-json'], stderr=subprocess.DEVNULL, text=True)
j = json.loads(out)
servers = j.get('servers', {}).get('value', {})
return servers # {name: ip}
except Exception:
return {}
def load_host_vars(name):
"""Load host_vars/<name>.yml if it exists.
The inventory script is ansible/inventory_from_yaml.py. Ansible does not
auto-load a host_vars directory next to a script inventory, so this has
to emit hostvars itself. Look in ansible/inventory/host_vars first (where
CoulombCore.yml actually lives), then the unused repo-root path.
"""
script_dir = os.path.dirname(__file__)
candidates = [
os.path.join(script_dir, 'inventory', 'host_vars', f'{name}.yml'),
os.path.join(script_dir, 'inventory', 'host_vars', f'{name}.yaml'),
os.path.join(script_dir, '..', 'inventory', 'host_vars', f'{name}.yml'),
os.path.join(script_dir, '..', 'inventory', 'host_vars', f'{name}.yaml'),
]
for path in candidates:
if os.path.exists(path):
with open(path) as f:
return yaml.safe_load(f) or {}
return {}
def main():
server_list = load_servers()
tf = load_tf_outputs()
host_names = []
hostvars = {}
for s in server_list:
name = s['name']
host_names.append(name)
hvars = {
"ansible_host": tf.get(name) or s.get('ip'),
"ansible_user": s.get('ssh_user', 'admin'),
}
if s.get('ssh_key'):
hvars["ansible_ssh_private_key_file"] = s['ssh_key']
hvars.update(load_host_vars(name))
hostvars[name] = hvars
inv = {
"all": {"hosts": host_names},
"_meta": {"hostvars": hostvars}
}
print(json.dumps(inv))
if __name__ == "__main__":
main()