feat(slice-1): implement tracer bullet pipeline with PyYAML check and pure-python fallback
This commit is contained in:
1 parent
937acc2548
commit
68802710b0
12 files changed
+331
-1
No files matched your search
@@ -0,0 +1 @@
|
||||
# Exporters package
|
||||
@@ -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"
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user