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

@@ -0,0 +1 @@
# Collectors package
+9
View File
@@ -0,0 +1,9 @@
from abc import ABC, abstractmethod
from typing import List
from inventory_collector.models import HostRecord
class BaseCollector(ABC):
@abstractmethod
def collect(self) -> List[HostRecord]:
"""Collect host records from source."""
raise NotImplementedError
@@ -0,0 +1,263 @@
import re
from pathlib import Path
from typing import Any, Dict, List, Set
from inventory_collector import get_yaml_module
from inventory_collector.collectors.base import BaseCollector
from inventory_collector.models import HostRecord
class StaticFileCollector(BaseCollector):
"""Collects hosts from static inventory files in YAML or INI format."""
def __init__(self, file_path: Path, default_user: str = "lain", default_port: int = 22) -> None:
self.file_path = Path(file_path).expanduser().resolve()
self.default_user = default_user
self.default_port = default_port
def collect(self) -> List[HostRecord]:
if not self.file_path.exists():
return []
content = self.file_path.read_text(encoding="utf-8")
ext = self.file_path.suffix.lower()
if ext in (".yaml", ".yml"):
return self._parse_yaml(content)
return self._parse_ini(content)
def _parse_yaml(self, content: str) -> List[HostRecord]:
yaml = get_yaml_module()
data: Dict[str, Any] = {}
if yaml:
data = yaml.safe_load(content) or {}
else:
# Fallback simple dictionary line parser if PyYAML is not present
data = self._fallback_yaml_parse(content)
records: List[HostRecord] = []
hosts_block = data.get("hosts", {})
# Format 1: Top-level "hosts:" mapping
if isinstance(hosts_block, dict):
for name, details in hosts_block.items():
if not isinstance(details, dict):
continue
ip = str(details.get("ansible_host", details.get("ip", name)))
user = str(details.get("ansible_user", details.get("user", self.default_user)))
port = int(details.get("ansible_port", details.get("port", self.default_port)))
groups = list(details.get("groups", []))
tags = list(details.get("tags", []))
vars_dict = {k: v for k, v in details.items() if k not in ("ansible_host", "ip", "ansible_user", "user", "ansible_port", "port", "groups", "tags")}
records.append(HostRecord(
name=str(name),
ansible_host=ip,
ansible_user=user,
ansible_port=port,
groups=groups,
tags=tags,
variables=vars_dict,
source=f"static:{self.file_path.name}"
))
# Check for groups block to add memberships
groups_block = data.get("groups", {})
if isinstance(groups_block, dict):
hosts_by_name = {r.name: r for r in records}
for grp_name, member_names in groups_block.items():
if isinstance(member_names, list):
for m_name in member_names:
if m_name in hosts_by_name:
h = hosts_by_name[m_name]
if grp_name not in h.groups:
new_groups = list(h.groups) + [grp_name]
hosts_by_name[m_name] = HostRecord(
name=h.name,
ansible_host=h.ansible_host,
ansible_user=h.ansible_user,
ansible_port=h.ansible_port,
ansible_ssh_private_key_file=h.ansible_ssh_private_key_file,
groups=new_groups,
tags=h.tags,
description=h.description,
variables=h.variables,
source=h.source
)
records = list(hosts_by_name.values())
return records
def _fallback_yaml_parse(self, content: str) -> Dict[str, Any]:
"""Indentation-aware pure-python parser for basic yaml inventory structures."""
result: Dict[str, Any] = {"hosts": {}, "groups": {}}
current_section = None
current_item = None
current_list_prop = None
for raw_line in content.splitlines():
line = raw_line.rstrip()
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
indent = len(line) - len(line.lstrip(" "))
# Top level section (indent == 0)
if indent == 0 and stripped.endswith(":"):
section_name = stripped[:-1].strip()
if section_name in ("hosts", "groups"):
current_section = section_name
current_item = None
current_list_prop = None
else:
current_section = None
continue
if current_section == "hosts":
if ":" in stripped and not stripped.startswith("-"):
k, v = stripped.split(":", 1)
k = k.strip()
v = v.strip().strip("'\"")
if not v:
if indent <= 2:
current_item = k
result["hosts"][current_item] = {"groups": [], "tags": []}
current_list_prop = None
elif current_item and k in ("groups", "tags"):
current_list_prop = k
else:
current_list_prop = None
else:
if current_item:
result["hosts"][current_item][k] = v
current_list_prop = None
elif stripped.startswith("-") and current_item and current_list_prop:
val = stripped[1:].strip().strip("'\"")
if val:
result["hosts"][current_item][current_list_prop].append(val)
elif current_section == "groups":
if ":" in stripped and not stripped.startswith("-"):
k, _ = stripped.split(":", 1)
current_item = k.strip()
if current_item not in result["groups"]:
result["groups"][current_item] = []
elif stripped.startswith("-") and current_item:
val = stripped[1:].strip().strip("'\"")
if val:
result["groups"][current_item].append(val)
return result
def _parse_ini(self, content: str) -> List[HostRecord]:
raw_hosts: Dict[str, Dict[str, Any]] = {}
group_members: Dict[str, List[str]] = {}
group_vars: Dict[str, Dict[str, Any]] = {}
group_children: Dict[str, List[str]] = {}
current_group = "ungrouped"
current_type = "hosts" # "hosts", "vars", "children"
for line in content.splitlines():
line = line.strip()
if not line or line.startswith(("#", ";")):
continue
# Strip inline comments
if " #" in line:
line = line.split(" #")[0].strip()
elif " ;" in line:
line = line.split(" ;")[0].strip()
# Section header [group_name], [group_name:vars], [group_name:children]
if line.startswith("[") and line.endswith("]"):
header = line[1:-1].strip()
if ":" in header:
parts = header.split(":", 1)
current_group = parts[0].strip()
current_type = parts[1].strip()
else:
current_group = header
current_type = "hosts"
continue
if current_type == "vars":
if "=" in line:
k, v = line.split("=", 1)
k = k.strip()
v = v.strip().strip("'\"")
if current_group not in group_vars:
group_vars[current_group] = {}
group_vars[current_group][k] = v
continue
if current_type == "children":
child_group = line.strip()
if child_group:
if current_group not in group_children:
group_children[current_group] = []
if child_group not in group_children[current_group]:
group_children[current_group].append(child_group)
continue
# Default: host line in current_group
tokens = line.split()
if not tokens:
continue
hostname = tokens[0]
host_params: Dict[str, Any] = {}
for tok in tokens[1:]:
if "=" in tok:
k, v = tok.split("=", 1)
host_params[k.strip()] = v.strip().strip("'\"")
if hostname not in raw_hosts:
raw_hosts[hostname] = {
"ansible_host": host_params.get("ansible_host", hostname),
"ansible_user": host_params.get("ansible_user", None),
"ansible_port": int(host_params.get("ansible_port", self.default_port)),
"groups": set(),
"variables": {k: v for k, v in host_params.items() if k not in ("ansible_host", "ansible_user", "ansible_port")}
}
if current_group != "ungrouped":
raw_hosts[hostname]["groups"].add(current_group)
if current_group not in group_members:
group_members[current_group] = []
if hostname not in group_members[current_group]:
group_members[current_group].append(hostname)
# Propagate child groups to parent groups recursively
def resolve_children(parent: str) -> Set[str]:
all_hosts: Set[str] = set(group_members.get(parent, []))
for child in group_children.get(parent, []):
all_hosts.update(resolve_children(child))
return all_hosts
for parent in group_children.keys():
all_descendants = resolve_children(parent)
for h_name in all_descendants:
if h_name in raw_hosts:
raw_hosts[h_name]["groups"].add(parent)
# Apply group_vars if host does not have explicit user
records: List[HostRecord] = []
for name, data in raw_hosts.items():
user = data["ansible_user"]
if not user:
# Check if any assigned group has ansible_user defined in vars
for grp in data["groups"]:
if grp in group_vars and "ansible_user" in group_vars[grp]:
user = group_vars[grp]["ansible_user"]
break
if not user:
user = self.default_user
records.append(HostRecord(
name=name,
ansible_host=data["ansible_host"],
ansible_user=user,
ansible_port=data["ansible_port"],
groups=sorted(list(data["groups"])),
variables=data["variables"],
source=f"static:{self.file_path.name}"
))
return records