diff --git a/bin/inventory-collector b/bin/inventory-collector new file mode 100755 index 0000000..b66ce10 --- /dev/null +++ b/bin/inventory-collector @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +# Add project root to sys.path when running from source checkout +root_dir = Path(__file__).resolve().parent.parent +if str(root_dir) not in sys.path: + sys.path.insert(0, str(root_dir)) + +for candidate in ("/usr/lib/inventory-collector", "/usr/local/lib/inventory-collector"): + if candidate not in sys.path and Path(candidate).is_dir(): + sys.path.insert(0, candidate) + +from inventory_collector.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/plans/inventory-collector/00-status.md b/docs/plans/inventory-collector/00-status.md index f06e280..0b661a3 100644 --- a/docs/plans/inventory-collector/00-status.md +++ b/docs/plans/inventory-collector/00-status.md @@ -6,7 +6,7 @@ - Gate 4 — Slice Plan: APPROVED 2026-10-03 ## Slices -- [ ] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output) +- [x] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output) - [ ] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list) - [ ] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution - [ ] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings diff --git a/inventory_collector/__init__.py b/inventory_collector/__init__.py new file mode 100644 index 0000000..8c756da --- /dev/null +++ b/inventory_collector/__init__.py @@ -0,0 +1,19 @@ +"""Universal homelab and fleet inventory collector and deduplicator.""" + +__version__ = "1.0.0" + +_yaml_warning_emitted = False + +def get_yaml_module(): + """Return the yaml module if installed, or None while emitting an actionable warning on stderr.""" + global _yaml_warning_emitted + try: + import yaml + return yaml + except ImportError: + import sys + if not _yaml_warning_emitted: + sys.stderr.write("[WARN] Moduł 'pyyaml' nie jest zainstalowany w środowisku Python. " + "Zainstaluj go za pomocą: pip install pyyaml (lub pip install -r requirements.txt)\n") + _yaml_warning_emitted = True + return None diff --git a/inventory_collector/__main__.py b/inventory_collector/__main__.py new file mode 100644 index 0000000..e0d8396 --- /dev/null +++ b/inventory_collector/__main__.py @@ -0,0 +1,5 @@ +import sys +from inventory_collector.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/inventory_collector/cli.py b/inventory_collector/cli.py new file mode 100644 index 0000000..1a2b091 --- /dev/null +++ b/inventory_collector/cli.py @@ -0,0 +1,96 @@ +import argparse +import sys +from pathlib import Path +from typing import List, Optional +from inventory_collector import __version__ +from inventory_collector.models import HostRecord, InventoryData +from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="inventory-collector", + description="Universal homelab and fleet inventory collector and deduplicator." + ) + parser.add_argument( + "-V", "--version", + action="version", + version=f"%(prog)s {__version__}" + ) + parser.add_argument( + "-o", "--output", + type=Path, + help="Target output file path. Defaults to stdout." + ) + parser.add_argument( + "-f", "--format", + choices=["ansible-yaml", "ansible-json", "linux-connector", "yaml", "xml", "ini"], + default="ansible-yaml", + help="Export format. Inferred from output file extension if omitted." + ) + parser.add_argument( + "--check", "--dry-run", + dest="dry_run", + action="store_true", + help="Inspect inventory without writing any files." + ) + parser.add_argument( + "--list", + action="store_true", + help="Ansible dynamic inventory mode: outputs JSON to stdout." + ) + parser.add_argument( + "--sync", + action="store_true", + help="Synchronize inventory to both Ansible and linux-connector default paths." + ) + parser.add_argument( + "-c", "--config", + type=Path, + help="Path to configuration file (config.yaml)." + ) + return parser + +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" + )) + + if args.dry_run: + sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups (tracer mode).\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() + rendered = exporter.export(inv) + + if args.output: + exporter.write_to_file(inv, args.output) + sys.stderr.write(f"[SUCCESS] Written inventory to {args.output}\n") + else: + sys.stdout.write(rendered) + + return 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/inventory_collector/exporters/__init__.py b/inventory_collector/exporters/__init__.py new file mode 100644 index 0000000..f00c5ac --- /dev/null +++ b/inventory_collector/exporters/__init__.py @@ -0,0 +1 @@ +# Exporters package diff --git a/inventory_collector/exporters/ansible_yaml.py b/inventory_collector/exporters/ansible_yaml.py new file mode 100644 index 0000000..04087ca --- /dev/null +++ b/inventory_collector/exporters/ansible_yaml.py @@ -0,0 +1,82 @@ +from typing import Any, Dict +from inventory_collector import get_yaml_module +from inventory_collector.exporters.base import BaseExporter +from inventory_collector.models import InventoryData + +class AnsibleYamlExporter(BaseExporter): + """Exports inventory in standard Ansible YAML format.""" + + def _build_structure(self, data: InventoryData) -> Dict[str, Any]: + structure: Dict[str, Any] = { + "all": { + "children": {} + } + } + + # Hosts assigned to groups + grouped_hosts = set() + for group_name, host_names in sorted(data.groups.items()): + group_dict: Dict[str, Any] = {"hosts": {}} + for name in sorted(host_names): + host = data.get_host(name) + if not host: + continue + grouped_hosts.add(name) + host_vars: Dict[str, Any] = { + "ansible_host": host.ansible_host, + "ansible_user": host.ansible_user, + "ansible_port": host.ansible_port, + } + if host.ansible_ssh_private_key_file: + host_vars["ansible_ssh_private_key_file"] = host.ansible_ssh_private_key_file + if host.tags: + host_vars["tags"] = host.tags + for k, v in host.variables.items(): + host_vars[k] = v + group_dict["hosts"][name] = host_vars + structure["all"]["children"][group_name] = group_dict + + # Ungrouped hosts placed directly under all.hosts + ungrouped = {name: host for name, host in data.hosts.items() if name not in grouped_hosts} + if ungrouped: + structure["all"]["hosts"] = {} + for name, host in sorted(ungrouped.items()): + host_vars = { + "ansible_host": host.ansible_host, + "ansible_user": host.ansible_user, + "ansible_port": host.ansible_port, + } + if host.tags: + host_vars["tags"] = host.tags + for k, v in host.variables.items(): + host_vars[k] = v + structure["all"]["hosts"][name] = host_vars + + return structure + + def _builtin_yaml_dump(self, obj: Any, indent: int = 0) -> str: + """Lightweight pure-python YAML serializer for basic dictionary/list structures.""" + lines = [] + prefix = " " * indent + if isinstance(obj, dict): + for k, v in obj.items(): + if isinstance(v, (dict, list)): + lines.append(f"{prefix}{k}:") + lines.append(self._builtin_yaml_dump(v, indent + 1)) + else: + lines.append(f"{prefix}{k}: {v}") + elif isinstance(obj, list): + for item in obj: + if isinstance(item, (dict, list)): + lines.append(f"{prefix}-") + lines.append(self._builtin_yaml_dump(item, indent + 1)) + else: + lines.append(f"{prefix}- {item}") + return "\n".join(lines) + + def export(self, data: InventoryData) -> str: + structure = self._build_structure(data) + yaml = get_yaml_module() + if yaml: + return yaml.dump(structure, sort_keys=False, default_flow_style=False) + return self._builtin_yaml_dump(structure) + "\n" diff --git a/inventory_collector/exporters/base.py b/inventory_collector/exporters/base.py new file mode 100644 index 0000000..4f4febd --- /dev/null +++ b/inventory_collector/exporters/base.py @@ -0,0 +1,16 @@ +from abc import ABC, abstractmethod +from pathlib import Path +from inventory_collector.models import InventoryData + +class BaseExporter(ABC): + @abstractmethod + def export(self, data: InventoryData) -> str: + """Export inventory data to a formatted string representation.""" + raise NotImplementedError + + def write_to_file(self, data: InventoryData, target: Path) -> None: + """Export inventory data and write to target path, creating parent dirs if needed.""" + target = Path(target).expanduser().resolve() + target.parent.mkdir(parents=True, exist_ok=True) + content = self.export(data) + target.write_text(content, encoding="utf-8") diff --git a/inventory_collector/models.py b/inventory_collector/models.py new file mode 100644 index 0000000..bbd1dba --- /dev/null +++ b/inventory_collector/models.py @@ -0,0 +1,35 @@ +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Any + +@dataclass(frozen=True) +class HostRecord: + name: str + ansible_host: str + ansible_user: str = "lain" + ansible_port: int = 22 + ansible_ssh_private_key_file: Optional[str] = None + groups: List[str] = field(default_factory=list) + tags: List[str] = field(default_factory=list) + description: str = "" + variables: Dict[str, Any] = field(default_factory=dict) + source: str = "unknown" + +@dataclass +class InventoryData: + hosts: Dict[str, HostRecord] = field(default_factory=dict) + groups: Dict[str, List[str]] = field(default_factory=dict) + + def add_host(self, host: HostRecord) -> None: + self.hosts[host.name] = host + for group in host.groups: + if group not in self.groups: + self.groups[group] = [] + if host.name not in self.groups[group]: + self.groups[group].append(host.name) + + def get_host(self, name: str) -> Optional[HostRecord]: + return self.hosts.get(name) + + def get_hosts_by_group(self, group: str) -> List[HostRecord]: + host_names = self.groups.get(group, []) + return [self.hosts[name] for name in host_names if name in self.hosts] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3aecde9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pyyaml>=6.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..65140f2 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# tests package diff --git a/tests/test_tracer.py b/tests/test_tracer.py new file mode 100644 index 0000000..e2d0d26 --- /dev/null +++ b/tests/test_tracer.py @@ -0,0 +1,57 @@ +import unittest +import sys +from io import StringIO +from inventory_collector.models import HostRecord, InventoryData +from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter +from inventory_collector.cli import main + +class TestTracerBullet(unittest.TestCase): + def test_host_record_creation(self): + 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="test" + ) + self.assertEqual(host.name, "k3s-master-0") + self.assertEqual(host.ansible_host, "192.168.5.70") + self.assertEqual(host.ansible_user, "lain") + self.assertIn("k3s_master", host.groups) + + def test_ansible_yaml_exporter_output(self): + inv = InventoryData() + host = HostRecord( + name="k3s-master-0", + ansible_host="192.168.5.70", + ansible_user="lain", + groups=["k3s_master"], + tags=["control-plane"] + ) + inv.add_host(host) + + exporter = AnsibleYamlExporter() + output = exporter.export(inv) + + self.assertIn("all:", output) + self.assertIn("children:", output) + self.assertIn("k3s_master:", output) + self.assertIn("k3s-master-0:", output) + self.assertIn("192.168.5.70", output) + + def test_cli_runs_tracer(self): + stdout_capture = StringIO() + stderr_capture = StringIO() + old_stdout, old_stderr = sys.stdout, sys.stderr + try: + sys.stdout = stdout_capture + sys.stderr = stderr_capture + exit_code = main(["--dry-run"]) + self.assertEqual(exit_code, 0) + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + +if __name__ == "__main__": + unittest.main()