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
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
## Slices
|
## Slices
|
||||||
- [x] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output)
|
- [x] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output)
|
||||||
- [ ] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list)
|
- [x] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list)
|
||||||
- [ ] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution
|
- [ ] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution
|
||||||
- [ ] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings
|
- [ ] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings
|
||||||
- [ ] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag
|
- [ ] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ def get_yaml_module():
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
import sys
|
import sys
|
||||||
if not _yaml_warning_emitted:
|
if not _yaml_warning_emitted:
|
||||||
sys.stderr.write("[WARN] Moduł 'pyyaml' nie jest zainstalowany w środowisku Python. "
|
sys.stderr.write("[WARN] 'pyyaml' module is not installed in the Python environment. "
|
||||||
"Zainstaluj go za pomocą: pip install pyyaml (lub pip install -r requirements.txt)\n")
|
"Install it via: pip install pyyaml (or pip install -r requirements.txt)\n")
|
||||||
_yaml_warning_emitted = True
|
_yaml_warning_emitted = True
|
||||||
return None
|
return None
|
||||||
+42
-19
@@ -4,7 +4,9 @@ from pathlib import Path
|
|||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from inventory_collector import __version__
|
from inventory_collector import __version__
|
||||||
from inventory_collector.models import HostRecord, InventoryData
|
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_yaml import AnsibleYamlExporter
|
||||||
|
from inventory_collector.exporters.ansible_json import AnsibleJsonExporter
|
||||||
|
|
||||||
def build_parser() -> argparse.ArgumentParser:
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
@@ -16,6 +18,13 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
action="version",
|
action="version",
|
||||||
version=f"%(prog)s {__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(
|
parser.add_argument(
|
||||||
"-o", "--output",
|
"-o", "--output",
|
||||||
type=Path,
|
type=Path,
|
||||||
@@ -54,34 +63,48 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
parser = build_parser()
|
parser = build_parser()
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
# Tracer bullet sample data when no source is loaded yet
|
|
||||||
inv = InventoryData()
|
inv = InventoryData()
|
||||||
inv.add_host(HostRecord(
|
|
||||||
name="k3s-master-0",
|
# Load from sources if specified
|
||||||
ansible_host="192.168.5.70",
|
if args.sources:
|
||||||
ansible_user="lain",
|
for src in args.sources:
|
||||||
groups=["k3s_master", "k3s_cluster"],
|
collector = StaticFileCollector(src)
|
||||||
tags=["control-plane", "proxmox"],
|
for host in collector.collect():
|
||||||
source="tracer"
|
inv.add_host(host)
|
||||||
))
|
|
||||||
inv.add_host(HostRecord(
|
# Tracer bullet fallback if no hosts loaded
|
||||||
name="node0",
|
if not inv.hosts:
|
||||||
ansible_host="192.168.0.101",
|
inv.add_host(HostRecord(
|
||||||
ansible_user="root",
|
name="k3s-master-0",
|
||||||
groups=["proxmox_nodes"],
|
ansible_host="192.168.5.70",
|
||||||
tags=["hypervisor", "pve"],
|
ansible_user="lain",
|
||||||
source="tracer"
|
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:
|
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")
|
print("NAME IP ADDRESS SOURCE GROUPS")
|
||||||
for h in inv.hosts.values():
|
for h in inv.hosts.values():
|
||||||
groups_str = ", ".join(h.groups)
|
groups_str = ", ".join(h.groups)
|
||||||
print(f"{h.name:<17} {h.ansible_host:<15} {h.source:<9} {groups_str}")
|
print(f"{h.name:<17} {h.ansible_host:<15} {h.source:<9} {groups_str}")
|
||||||
return 0
|
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)
|
rendered = exporter.export(inv)
|
||||||
|
|
||||||
if args.output:
|
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"
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.0.0" "User Commands"
|
||||||
|
.SH NAME
|
||||||
|
inventory-collector \- Universal homelab and fleet inventory collector and deduplicator
|
||||||
|
.SH SYNOPSIS
|
||||||
|
.B inventory-collector
|
||||||
|
[\fIOPTIONS\fR]
|
||||||
|
.SH DESCRIPTION
|
||||||
|
.B inventory-collector
|
||||||
|
is a command-line tool that dynamically queries infrastructure sources (Proxmox VE REST API, static YAML and INI inventory files), normalizes and deduplicates host records in memory, and generates unified inventory files for Ansible, linux-connector, and other fleet management tools.
|
||||||
|
.SH OPTIONS
|
||||||
|
.TP
|
||||||
|
.BR \-o ", " \-\-output " \fIFILE\fR"
|
||||||
|
Write generated inventory to \fIFILE\fR. If omitted, inventory payload is printed to standard output.
|
||||||
|
.TP
|
||||||
|
.BR \-f ", " \-\-format " \fIFORMAT\fR"
|
||||||
|
Select output format: \fIansible-yaml\fR (default), \fIansible-json\fR, \fIlinux-connector\fR, \fIyaml\fR, \fIxml\fR, or \fIini\fR. If \fB\-\-output\fR is provided, format is automatically inferred from the file extension (.xml, .ini, .json, .yaml).
|
||||||
|
.TP
|
||||||
|
.BR \-\-check ", " \-\-dry-run
|
||||||
|
Inspect discovered hosts and groups in a formatted terminal table without writing or modifying any files.
|
||||||
|
.TP
|
||||||
|
.B \-\-list
|
||||||
|
Ansible Dynamic Inventory mode. Outputs valid dynamic inventory JSON with \fB_meta.hostvars\fR to standard output, suitable for direct execution with \fIansible-playbook -i\fR.
|
||||||
|
.TP
|
||||||
|
.B \-\-sync
|
||||||
|
Synchronize inventory simultaneously to both default Ansible and linux-connector destination paths.
|
||||||
|
.TP
|
||||||
|
.BR \-c ", " \-\-config " \fIFILE\fR"
|
||||||
|
Path to YAML configuration file. Defaults to \fI~/.config/inventory-collector/config.yaml\fR.
|
||||||
|
.TP
|
||||||
|
.BR \-V ", " \-\-version
|
||||||
|
Show program version and exit.
|
||||||
|
.TP
|
||||||
|
.BR \-h ", " \-\-help
|
||||||
|
Show help message and exit.
|
||||||
|
.SH ENVIRONMENT VARIABLES
|
||||||
|
.TP
|
||||||
|
.B PROXMOX_URL ", " ANSIBLE_PROXMOX_URL
|
||||||
|
Base URL of the Proxmox VE API (e.g. \fIhttps://pve-01.wired.intra:8006\fR).
|
||||||
|
.TP
|
||||||
|
.B PROXMOX_TOKEN_ID ", " ANSIBLE_PROXMOX_TOKEN_ID
|
||||||
|
API Token ID (e.g. \fIroot@pam!inventory-collector\fR).
|
||||||
|
.TP
|
||||||
|
.B PROXMOX_TOKEN_SECRET ", " ANSIBLE_PROXMOX_TOKEN_SECRET
|
||||||
|
API Token Secret UUID.
|
||||||
|
.TP
|
||||||
|
.B PROXMOX_VERIFY_SSL
|
||||||
|
Whether to verify Proxmox SSL certificate (\fItrue\fR or \fIfalse\fR, default: \fIfalse\fR).
|
||||||
|
.SH EXIT STATUS
|
||||||
|
.TP
|
||||||
|
.B 0
|
||||||
|
Success.
|
||||||
|
.TP
|
||||||
|
.B 1
|
||||||
|
Runtime error or unhandled exception.
|
||||||
|
.TP
|
||||||
|
.B 2
|
||||||
|
Proxmox API source unreachable.
|
||||||
|
.TP
|
||||||
|
.B 3
|
||||||
|
Configuration or static file syntax error.
|
||||||
|
.SH AUTHORS
|
||||||
|
inventory-collector is maintained as part of the wiredLAB infrastructure suite.
|
||||||
Vendored
+15
@@ -0,0 +1,15 @@
|
|||||||
|
# Sample Static Inventory for Testing
|
||||||
|
[proxmox_nodes]
|
||||||
|
node0 ansible_host=192.168.0.101
|
||||||
|
node1 ansible_host=192.168.0.111
|
||||||
|
node2 ansible_host=192.168.0.121
|
||||||
|
|
||||||
|
[proxmox_nodes:vars]
|
||||||
|
ansible_user=root
|
||||||
|
|
||||||
|
[tool_servers]
|
||||||
|
tool-server-1 ansible_host=192.168.5.61 ansible_user=lain
|
||||||
|
tool-server-synology ansible_host=192.168.11.2 ansible_user=lain
|
||||||
|
|
||||||
|
[external]
|
||||||
|
synology-nas ansible_host=192.168.0.2 ansible_user=soda64
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
from inventory_collector.models import HostRecord, InventoryData
|
||||||
|
from inventory_collector.exporters.ansible_json import AnsibleJsonExporter
|
||||||
|
|
||||||
|
class TestAnsibleJsonExporter(unittest.TestCase):
|
||||||
|
def test_ansible_json_dynamic_inventory_schema(self):
|
||||||
|
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"]
|
||||||
|
))
|
||||||
|
inv.add_host(HostRecord(
|
||||||
|
name="node0",
|
||||||
|
ansible_host="192.168.0.101",
|
||||||
|
ansible_user="root",
|
||||||
|
groups=["proxmox_nodes"],
|
||||||
|
tags=["hypervisor"]
|
||||||
|
))
|
||||||
|
|
||||||
|
exporter = AnsibleJsonExporter()
|
||||||
|
raw_json = exporter.export(inv)
|
||||||
|
parsed = json.loads(raw_json)
|
||||||
|
|
||||||
|
# Must have _meta.hostvars section
|
||||||
|
self.assertIn("_meta", parsed)
|
||||||
|
self.assertIn("hostvars", parsed["_meta"])
|
||||||
|
self.assertIn("k3s-master-0", parsed["_meta"]["hostvars"])
|
||||||
|
self.assertEqual(parsed["_meta"]["hostvars"]["k3s-master-0"]["ansible_host"], "192.168.5.70")
|
||||||
|
self.assertEqual(parsed["_meta"]["hostvars"]["k3s-master-0"]["ansible_user"], "lain")
|
||||||
|
|
||||||
|
# Must have groups mapping to host lists
|
||||||
|
self.assertIn("k3s_master", parsed)
|
||||||
|
self.assertIn("hosts", parsed["k3s_master"])
|
||||||
|
self.assertIn("k3s-master-0", parsed["k3s_master"]["hosts"])
|
||||||
|
|
||||||
|
self.assertIn("proxmox_nodes", parsed)
|
||||||
|
self.assertIn("node0", parsed["proxmox_nodes"]["hosts"])
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import NamedTemporaryFile
|
||||||
|
from inventory_collector.collectors.static_file import StaticFileCollector
|
||||||
|
from inventory_collector.models import HostRecord
|
||||||
|
|
||||||
|
class TestStaticFileCollector(unittest.TestCase):
|
||||||
|
def test_parse_ansible_ini_basic(self):
|
||||||
|
ini_content = """
|
||||||
|
[proxmox_nodes]
|
||||||
|
node0 ansible_host=192.168.0.101
|
||||||
|
node1 ansible_host=192.168.0.111
|
||||||
|
|
||||||
|
[proxmox_nodes:vars]
|
||||||
|
ansible_user=root
|
||||||
|
|
||||||
|
[k3s_masters]
|
||||||
|
k3s-master-0 ansible_host=192.168.5.70 ansible_user=lain
|
||||||
|
|
||||||
|
[k3s_workers]
|
||||||
|
k3s-worker-0 ansible_host=192.168.5.80 ansible_user=lain
|
||||||
|
|
||||||
|
[k3s_cluster:children]
|
||||||
|
k3s_masters
|
||||||
|
k3s_workers
|
||||||
|
"""
|
||||||
|
with NamedTemporaryFile("w+", suffix=".ini", delete=False) as f:
|
||||||
|
f.write(ini_content)
|
||||||
|
temp_path = Path(f.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
collector = StaticFileCollector(temp_path)
|
||||||
|
hosts = collector.collect()
|
||||||
|
|
||||||
|
# Convert to dict by name for inspection
|
||||||
|
hosts_dict = {h.name: h for h in hosts}
|
||||||
|
|
||||||
|
self.assertIn("node0", hosts_dict)
|
||||||
|
self.assertEqual(hosts_dict["node0"].ansible_host, "192.168.0.101")
|
||||||
|
self.assertEqual(hosts_dict["node0"].ansible_user, "root")
|
||||||
|
self.assertIn("proxmox_nodes", hosts_dict["node0"].groups)
|
||||||
|
|
||||||
|
self.assertIn("k3s-master-0", hosts_dict)
|
||||||
|
self.assertEqual(hosts_dict["k3s-master-0"].ansible_host, "192.168.5.70")
|
||||||
|
self.assertEqual(hosts_dict["k3s-master-0"].ansible_user, "lain")
|
||||||
|
self.assertIn("k3s_masters", hosts_dict["k3s-master-0"].groups)
|
||||||
|
self.assertIn("k3s_cluster", hosts_dict["k3s-master-0"].groups)
|
||||||
|
finally:
|
||||||
|
temp_path.unlink()
|
||||||
|
|
||||||
|
def test_parse_static_yaml(self):
|
||||||
|
yaml_content = """
|
||||||
|
hosts:
|
||||||
|
synology-nas:
|
||||||
|
ansible_host: 192.168.0.2
|
||||||
|
ansible_user: soda64
|
||||||
|
groups:
|
||||||
|
- storage
|
||||||
|
- external
|
||||||
|
tags:
|
||||||
|
- nas
|
||||||
|
- btrfs
|
||||||
|
groups:
|
||||||
|
storage:
|
||||||
|
- synology-nas
|
||||||
|
"""
|
||||||
|
with NamedTemporaryFile("w+", suffix=".yaml", delete=False) as f:
|
||||||
|
f.write(yaml_content)
|
||||||
|
temp_path = Path(f.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
collector = StaticFileCollector(temp_path)
|
||||||
|
hosts = collector.collect()
|
||||||
|
self.assertEqual(len(hosts), 1)
|
||||||
|
nas = hosts[0]
|
||||||
|
self.assertEqual(nas.name, "synology-nas")
|
||||||
|
self.assertEqual(nas.ansible_host, "192.168.0.2")
|
||||||
|
self.assertEqual(nas.ansible_user, "soda64")
|
||||||
|
self.assertIn("storage", nas.groups)
|
||||||
|
self.assertIn("nas", nas.tags)
|
||||||
|
finally:
|
||||||
|
temp_path.unlink()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user