feat(slice-2): implement static file collector for YAML/INI and Ansible JSON dynamic inventory exporter
This commit is contained in:
1 parent
68802710b0
commit
951be389a1
11 files changed
+564
-22
No files matched your search
@@ -13,7 +13,7 @@ def get_yaml_module():
|
||||
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")
|
||||
sys.stderr.write("[WARN] 'pyyaml' module is not installed in the Python environment. "
|
||||
"Install it via: pip install pyyaml (or pip install -r requirements.txt)\n")
|
||||
_yaml_warning_emitted = True
|
||||
return None
|
||||
+42
-19
@@ -4,7 +4,9 @@ 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.exporters.ansible_yaml import AnsibleYamlExporter
|
||||
from inventory_collector.exporters.ansible_json import AnsibleJsonExporter
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -16,6 +18,13 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
action="version",
|
||||
version=f"%(prog)s {__version__}"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s", "--source",
|
||||
action="append",
|
||||
type=Path,
|
||||
dest="sources",
|
||||
help="Path to static inventory file (.ini or .yaml). Can be passed multiple times."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o", "--output",
|
||||
type=Path,
|
||||
@@ -54,34 +63,48 @@ 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"
|
||||
))
|
||||
|
||||
# Load from sources if specified
|
||||
if args.sources:
|
||||
for src in args.sources:
|
||||
collector = StaticFileCollector(src)
|
||||
for host in collector.collect():
|
||||
inv.add_host(host)
|
||||
|
||||
# Tracer bullet fallback if no hosts loaded
|
||||
if not inv.hosts:
|
||||
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")
|
||||
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups.\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()
|
||||
# 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()
|
||||
|
||||
rendered = exporter.export(inv)
|
||||
|
||||
if args.output:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# Collectors package
|
||||
@@ -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
|
||||
@@ -0,0 +1,40 @@
|
||||
import json
|
||||
from typing import Any, Dict
|
||||
from inventory_collector.exporters.base import BaseExporter
|
||||
from inventory_collector.models import InventoryData
|
||||
|
||||
class AnsibleJsonExporter(BaseExporter):
|
||||
"""Exports inventory in standard Ansible Dynamic Inventory JSON format with _meta.hostvars."""
|
||||
|
||||
def export(self, data: InventoryData) -> str:
|
||||
payload: Dict[str, Any] = {
|
||||
"_meta": {
|
||||
"hostvars": {}
|
||||
},
|
||||
"all": {
|
||||
"children": sorted(list(data.groups.keys()))
|
||||
}
|
||||
}
|
||||
|
||||
# Populate hostvars
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
hvars: 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:
|
||||
hvars["ansible_ssh_private_key_file"] = host.ansible_ssh_private_key_file
|
||||
if host.tags:
|
||||
hvars["tags"] = host.tags
|
||||
for k, v in host.variables.items():
|
||||
hvars[k] = v
|
||||
payload["_meta"]["hostvars"][name] = hvars
|
||||
|
||||
# Populate groups
|
||||
for grp_name, host_names in sorted(data.groups.items()):
|
||||
payload[grp_name] = {
|
||||
"hosts": sorted(host_names)
|
||||
}
|
||||
|
||||
return json.dumps(payload, indent=2) + "\n"
|
||||
Reference in new issue
Block a user