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
@@ -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