feat(slice-2): implement static file collector for YAML/INI and Ansible JSON dynamic inventory exporter

This commit is contained in:
soda64 committed 2026-10-03 08:56:59 +02:00
1 parent 68802710b0
commit 951be389a1
11 files changed
+564 -22

No files matched your search

+42 -19
View File
@@ -4,7 +4,9 @@ from pathlib import Path
from typing import List, Optional
from inventory_collector import __version__
from inventory_collector.models import HostRecord, InventoryData
from inventory_collector.collectors.static_file import StaticFileCollector
from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter
from inventory_collector.exporters.ansible_json import AnsibleJsonExporter
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
@@ -16,6 +18,13 @@ def build_parser() -> argparse.ArgumentParser:
action="version",
version=f"%(prog)s {__version__}"
)
parser.add_argument(
"-s", "--source",
action="append",
type=Path,
dest="sources",
help="Path to static inventory file (.ini or .yaml). Can be passed multiple times."
)
parser.add_argument(
"-o", "--output",
type=Path,
@@ -54,34 +63,48 @@ def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
# Tracer bullet sample data when no source is loaded yet
inv = InventoryData()
inv.add_host(HostRecord(
name="k3s-master-0",
ansible_host="192.168.5.70",
ansible_user="lain",
groups=["k3s_master", "k3s_cluster"],
tags=["control-plane", "proxmox"],
source="tracer"
))
inv.add_host(HostRecord(
name="node0",
ansible_host="192.168.0.101",
ansible_user="root",
groups=["proxmox_nodes"],
tags=["hypervisor", "pve"],
source="tracer"
))
# Load from sources if specified
if args.sources:
for src in args.sources:
collector = StaticFileCollector(src)
for host in collector.collect():
inv.add_host(host)
# Tracer bullet fallback if no hosts loaded
if not inv.hosts:
inv.add_host(HostRecord(
name="k3s-master-0",
ansible_host="192.168.5.70",
ansible_user="lain",
groups=["k3s_master", "k3s_cluster"],
tags=["control-plane", "proxmox"],
source="tracer"
))
inv.add_host(HostRecord(
name="node0",
ansible_host="192.168.0.101",
ansible_user="root",
groups=["proxmox_nodes"],
tags=["hypervisor", "pve"],
source="tracer"
))
if args.dry_run:
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups (tracer mode).\n")
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups.\n")
print("NAME IP ADDRESS SOURCE GROUPS")
for h in inv.hosts.values():
groups_str = ", ".join(h.groups)
print(f"{h.name:<17} {h.ansible_host:<15} {h.source:<9} {groups_str}")
return 0
exporter = AnsibleYamlExporter()
# Ansible Dynamic Inventory Mode (--list)
if args.list or args.format == "ansible-json" or (args.output and args.output.suffix.lower() == ".json"):
exporter = AnsibleJsonExporter()
else:
exporter = AnsibleYamlExporter()
rendered = exporter.export(inv)
if args.output: