feat(slice-5): implement extended exporters (linux-connector, generic yaml, xml, ini) and --sync mode
This commit is contained in:
1 parent
14a2032c42
commit
869fd241e7
7 files changed
+390
-17
No files matched your search
+66
-16
@@ -1,12 +1,46 @@
|
||||
import argparse
|
||||
import os
|
||||
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.collectors.static_file import StaticFileCollector
|
||||
from inventory_collector.collectors.proxmox import ProxmoxCollector
|
||||
from inventory_collector.engine import DeduplicationEngine
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter
|
||||
from inventory_collector.exporters.ansible_json import AnsibleJsonExporter
|
||||
from inventory_collector.exporters.linux_connector import LinuxConnectorExporter
|
||||
from inventory_collector.exporters.generic_yaml import GenericYamlExporter
|
||||
from inventory_collector.exporters.xml_exporter import XmlExporter
|
||||
from inventory_collector.exporters.ini_exporter import IniExporter
|
||||
|
||||
def get_exporter(fmt: str) -> BaseExporter:
|
||||
fmt_clean = fmt.lower().strip()
|
||||
if fmt_clean in ("ansible-yaml", "ansible"):
|
||||
return AnsibleYamlExporter()
|
||||
elif fmt_clean in ("ansible-json", "json"):
|
||||
return AnsibleJsonExporter()
|
||||
elif fmt_clean in ("linux-connector", "lc"):
|
||||
return LinuxConnectorExporter()
|
||||
elif fmt_clean in ("yaml", "generic-yaml"):
|
||||
return GenericYamlExporter()
|
||||
elif fmt_clean == "xml":
|
||||
return XmlExporter()
|
||||
elif fmt_clean == "ini":
|
||||
return IniExporter()
|
||||
return AnsibleYamlExporter()
|
||||
|
||||
def infer_format_from_path(path: Path) -> str:
|
||||
ext = path.suffix.lower()
|
||||
if ext == ".xml":
|
||||
return "xml"
|
||||
elif ext == ".ini":
|
||||
return "ini"
|
||||
elif ext == ".json":
|
||||
return "ansible-json"
|
||||
return "ansible-yaml"
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -33,7 +67,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
parser.add_argument(
|
||||
"-f", "--format",
|
||||
choices=["ansible-yaml", "ansible-json", "linux-connector", "yaml", "xml", "ini"],
|
||||
default="ansible-yaml",
|
||||
default=None,
|
||||
help="Export format. Inferred from output file extension if omitted."
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -63,20 +97,15 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
inv = InventoryData()
|
||||
|
||||
raw_records: List[HostRecord] = []
|
||||
|
||||
# Load from sources if specified
|
||||
# 1. Load from static sources if specified
|
||||
if args.sources:
|
||||
for src in args.sources:
|
||||
collector = StaticFileCollector(src)
|
||||
raw_records.extend(collector.collect())
|
||||
|
||||
# Check for Proxmox environment variables
|
||||
import os
|
||||
from inventory_collector.collectors.proxmox import ProxmoxCollector
|
||||
|
||||
# 2. Check for Proxmox environment variables
|
||||
pve_url = os.getenv("PROXMOX_URL") or os.getenv("ANSIBLE_PROXMOX_URL")
|
||||
pve_token_id = os.getenv("PROXMOX_TOKEN_ID") or os.getenv("ANSIBLE_PROXMOX_TOKEN_ID")
|
||||
pve_token_secret = os.getenv("PROXMOX_TOKEN_SECRET") or os.getenv("ANSIBLE_PROXMOX_TOKEN_SECRET")
|
||||
@@ -92,7 +121,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
)
|
||||
raw_records.extend(pve_collector.collect())
|
||||
|
||||
# Tracer bullet fallback if no hosts loaded
|
||||
# 3. Fallback tracer records if completely empty
|
||||
if not raw_records:
|
||||
raw_records.append(HostRecord(
|
||||
name="k3s-master-0",
|
||||
@@ -111,13 +140,14 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
source="tracer"
|
||||
))
|
||||
|
||||
from inventory_collector.engine import DeduplicationEngine
|
||||
# 4. Deduplicate and merge records in memory
|
||||
engine = DeduplicationEngine()
|
||||
inv, warnings = engine.process(raw_records)
|
||||
|
||||
for w in warnings:
|
||||
sys.stderr.write(f"[WARN] {w}\n")
|
||||
|
||||
# 5. Inspection / Dry-run Mode
|
||||
if args.dry_run:
|
||||
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups.\n")
|
||||
print("NAME IP ADDRESS SOURCE GROUPS")
|
||||
@@ -126,17 +156,37 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
print(f"{h.name:<17} {h.ansible_host:<15} {h.source:<9} {groups_str}")
|
||||
return 0
|
||||
|
||||
# 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()
|
||||
# 6. Ansible Dynamic Inventory Mode (--list)
|
||||
if args.list:
|
||||
sys.stdout.write(AnsibleJsonExporter().export(inv))
|
||||
return 0
|
||||
|
||||
# 7. Simultaneous Synchronization Mode (--sync)
|
||||
if args.sync:
|
||||
ansible_dest = Path("inventory/hosts.yaml")
|
||||
lc_dest = Path("~/.config/linux-connector/hosts.yaml").expanduser()
|
||||
|
||||
AnsibleYamlExporter().write_to_file(inv, ansible_dest)
|
||||
sys.stderr.write(f"[SUCCESS] Updated Ansible inventory: {ansible_dest}\n")
|
||||
|
||||
LinuxConnectorExporter().write_to_file(inv, lc_dest)
|
||||
sys.stderr.write(f"[SUCCESS] Updated linux-connector inventory: {lc_dest}\n")
|
||||
return 0
|
||||
|
||||
# 8. Standard Format Export
|
||||
if args.format:
|
||||
fmt = args.format
|
||||
elif args.output:
|
||||
fmt = infer_format_from_path(args.output)
|
||||
else:
|
||||
fmt = "ansible-yaml"
|
||||
|
||||
exporter = get_exporter(fmt)
|
||||
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")
|
||||
sys.stderr.write(f"[SUCCESS] Written {fmt} inventory to {args.output}\n")
|
||||
else:
|
||||
sys.stdout.write(rendered)
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
from typing import Any, Dict, List
|
||||
from inventory_collector import get_yaml_module
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.models import InventoryData
|
||||
|
||||
class GenericYamlExporter(BaseExporter):
|
||||
"""Exports inventory in clean, plain generic YAML format."""
|
||||
|
||||
def _build_structure(self, data: InventoryData) -> Dict[str, Any]:
|
||||
hosts_list: List[Dict[str, Any]] = []
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
h_dict: Dict[str, Any] = {
|
||||
"name": host.name,
|
||||
"ip": host.ansible_host,
|
||||
"user": host.ansible_user,
|
||||
"port": host.ansible_port,
|
||||
"groups": sorted(host.groups),
|
||||
"tags": sorted(host.tags),
|
||||
"source": host.source
|
||||
}
|
||||
hosts_list.append(h_dict)
|
||||
|
||||
groups_dict: Dict[str, List[str]] = {}
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
groups_dict[grp_name] = sorted(members)
|
||||
|
||||
return {
|
||||
"hosts": hosts_list,
|
||||
"groups": groups_dict
|
||||
}
|
||||
|
||||
def _builtin_yaml_dump(self, obj: Any, indent: int = 0) -> str:
|
||||
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):
|
||||
first = True
|
||||
for k, v in item.items():
|
||||
if first:
|
||||
if isinstance(v, (dict, list)):
|
||||
lines.append(f"{prefix}- {k}:")
|
||||
lines.append(self._builtin_yaml_dump(v, indent + 2))
|
||||
else:
|
||||
lines.append(f"{prefix}- {k}: {v}")
|
||||
first = False
|
||||
else:
|
||||
if isinstance(v, (dict, list)):
|
||||
lines.append(f"{prefix} {k}:")
|
||||
lines.append(self._builtin_yaml_dump(v, indent + 2))
|
||||
else:
|
||||
lines.append(f"{prefix} {k}: {v}")
|
||||
elif isinstance(item, 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"
|
||||
@@ -0,0 +1,46 @@
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.models import InventoryData
|
||||
|
||||
class IniExporter(BaseExporter):
|
||||
"""Exports inventory in standard Ansible INI format."""
|
||||
|
||||
def export(self, data: InventoryData) -> str:
|
||||
lines = []
|
||||
|
||||
# Hosts assigned to groups
|
||||
grouped_hosts = set()
|
||||
for grp_name, host_names in sorted(data.groups.items()):
|
||||
lines.append(f"[{grp_name}]")
|
||||
for h_name in sorted(host_names):
|
||||
host = data.get_host(h_name)
|
||||
if not host:
|
||||
continue
|
||||
grouped_hosts.add(h_name)
|
||||
parts = [host.name]
|
||||
if host.ansible_host:
|
||||
parts.append(f"ansible_host={host.ansible_host}")
|
||||
if host.ansible_user:
|
||||
parts.append(f"ansible_user={host.ansible_user}")
|
||||
if host.ansible_port != 22:
|
||||
parts.append(f"ansible_port={host.ansible_port}")
|
||||
if host.ansible_ssh_private_key_file:
|
||||
parts.append(f"ansible_ssh_private_key_file={host.ansible_ssh_private_key_file}")
|
||||
lines.append(" ".join(parts))
|
||||
lines.append("")
|
||||
|
||||
# Ungrouped hosts
|
||||
ungrouped = [h for name, h in sorted(data.hosts.items()) if name not in grouped_hosts]
|
||||
if ungrouped:
|
||||
lines.append("[ungrouped]")
|
||||
for host in ungrouped:
|
||||
parts = [host.name]
|
||||
if host.ansible_host:
|
||||
parts.append(f"ansible_host={host.ansible_host}")
|
||||
if host.ansible_user:
|
||||
parts.append(f"ansible_user={host.ansible_user}")
|
||||
if host.ansible_port != 22:
|
||||
parts.append(f"ansible_port={host.ansible_port}")
|
||||
lines.append(" ".join(parts))
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines).strip() + "\n"
|
||||
@@ -0,0 +1,76 @@
|
||||
from typing import Any, Dict, List
|
||||
from inventory_collector import get_yaml_module
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.models import InventoryData
|
||||
|
||||
class LinuxConnectorExporter(BaseExporter):
|
||||
"""Exports inventory in hosts.yaml format for linux-connector."""
|
||||
|
||||
def _build_structure(self, data: InventoryData) -> Dict[str, Any]:
|
||||
hosts_list: List[Dict[str, Any]] = []
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
h_dict: Dict[str, Any] = {
|
||||
"name": host.name,
|
||||
"hostname": host.ansible_host,
|
||||
"user": host.ansible_user,
|
||||
"port": host.ansible_port,
|
||||
"groups": sorted(host.groups),
|
||||
"tags": sorted(host.tags)
|
||||
}
|
||||
if host.ansible_ssh_private_key_file:
|
||||
h_dict["identity_file"] = host.ansible_ssh_private_key_file
|
||||
if host.description:
|
||||
h_dict["description"] = host.description
|
||||
hosts_list.append(h_dict)
|
||||
|
||||
groups_dict: Dict[str, List[str]] = {}
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
groups_dict[grp_name] = sorted(members)
|
||||
|
||||
return {
|
||||
"hosts": hosts_list,
|
||||
"groups": groups_dict
|
||||
}
|
||||
|
||||
def _builtin_yaml_dump(self, obj: Any, indent: int = 0) -> str:
|
||||
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 of dicts
|
||||
first = True
|
||||
for k, v in item.items():
|
||||
if first:
|
||||
if isinstance(v, (dict, list)):
|
||||
lines.append(f"{prefix}- {k}:")
|
||||
lines.append(self._builtin_yaml_dump(v, indent + 2))
|
||||
else:
|
||||
lines.append(f"{prefix}- {k}: {v}")
|
||||
first = False
|
||||
else:
|
||||
if isinstance(v, (dict, list)):
|
||||
lines.append(f"{prefix} {k}:")
|
||||
lines.append(self._builtin_yaml_dump(v, indent + 2))
|
||||
else:
|
||||
lines.append(f"{prefix} {k}: {v}")
|
||||
elif isinstance(item, 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"
|
||||
@@ -0,0 +1,52 @@
|
||||
import xml.dom.minidom
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.models import InventoryData
|
||||
|
||||
class XmlExporter(BaseExporter):
|
||||
"""Exports inventory in structured, pretty-printed XML format."""
|
||||
|
||||
def export(self, data: InventoryData) -> str:
|
||||
root = ET.Element("inventory")
|
||||
root.set("generated_at", datetime.now(timezone.utc).isoformat())
|
||||
|
||||
hosts_elem = ET.SubElement(root, "hosts")
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
h_elem = ET.SubElement(hosts_elem, "host")
|
||||
h_elem.set("name", host.name)
|
||||
h_elem.set("ip", host.ansible_host)
|
||||
h_elem.set("user", host.ansible_user)
|
||||
h_elem.set("port", str(host.ansible_port))
|
||||
h_elem.set("source", host.source)
|
||||
|
||||
if host.groups:
|
||||
groups_elem = ET.SubElement(h_elem, "groups")
|
||||
for grp in sorted(host.groups):
|
||||
g = ET.SubElement(groups_elem, "group")
|
||||
g.text = grp
|
||||
|
||||
if host.tags:
|
||||
tags_elem = ET.SubElement(h_elem, "tags")
|
||||
for t in sorted(host.tags):
|
||||
tag_elem = ET.SubElement(tags_elem, "tag")
|
||||
tag_elem.text = t
|
||||
|
||||
if host.variables:
|
||||
vars_elem = ET.SubElement(h_elem, "variables")
|
||||
for k, v in sorted(host.variables.items()):
|
||||
var_elem = ET.SubElement(vars_elem, "variable")
|
||||
var_elem.set("name", str(k))
|
||||
var_elem.text = str(v)
|
||||
|
||||
groups_elem = ET.SubElement(root, "groups")
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
g_elem = ET.SubElement(groups_elem, "group")
|
||||
g_elem.set("name", grp_name)
|
||||
for m in sorted(members):
|
||||
m_elem = ET.SubElement(g_elem, "member")
|
||||
m_elem.text = m
|
||||
|
||||
rough_string = ET.tostring(root, "utf-8")
|
||||
reparsed = xml.dom.minidom.parseString(rough_string)
|
||||
return reparsed.toprettyxml(indent=" ")
|
||||
Reference in new issue
Block a user