Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
598e5d7397 | ||
|
|
5fedc44c6b |
No files matched your search
@@ -6,7 +6,7 @@ _inventory_collector_completion() {
|
|||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||||
|
|
||||||
opts="-o --output -f --format -s --source --check --dry-run --list --sync -c --config -V --version -h --help"
|
opts="-o --output -f --format -s --source --check --dry-run --list --sync -q --quiet -v --verbose -c --config -t --tag --filter-tag -g --group --category --filter-group --source-type --filter-source --origin -V --version -h --help"
|
||||||
formats="ansible-yaml ansible-json linux-connector yaml xml ini"
|
formats="ansible-yaml ansible-json linux-connector yaml xml ini"
|
||||||
|
|
||||||
case "${prev}" in
|
case "${prev}" in
|
||||||
@@ -14,6 +14,10 @@ _inventory_collector_completion() {
|
|||||||
COMPREPLY=( $(compgen -W "${formats}" -- "${cur}") )
|
COMPREPLY=( $(compgen -W "${formats}" -- "${cur}") )
|
||||||
return 0
|
return 0
|
||||||
;;
|
;;
|
||||||
|
--source-type|--filter-source|--origin)
|
||||||
|
COMPREPLY=( $(compgen -W "proxmox static file plik k3s" -- "${cur}") )
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
-o|--output|-s|--source|-c|--config)
|
-o|--output|-s|--source|-c|--config)
|
||||||
COMPREPLY=( $(compgen -f -- "${cur}") )
|
COMPREPLY=( $(compgen -f -- "${cur}") )
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -19,7 +19,12 @@ _inventory_collector() {
|
|||||||
'(--check --dry-run)'{--check,--dry-run}'[Inspect inventory without writing any files]' \
|
'(--check --dry-run)'{--check,--dry-run}'[Inspect inventory without writing any files]' \
|
||||||
'--list[Ansible dynamic inventory mode: outputs JSON to stdout]' \
|
'--list[Ansible dynamic inventory mode: outputs JSON to stdout]' \
|
||||||
'--sync[Synchronize inventory to both Ansible and linux-connector default paths]' \
|
'--sync[Synchronize inventory to both Ansible and linux-connector default paths]' \
|
||||||
|
'(-q --quiet)'{-q,--quiet}'[Silence all informational and warning messages on stderr]' \
|
||||||
|
'(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \
|
||||||
'(-c --config)'{-c,--config}'[Path to configuration file]:file:_files' \
|
'(-c --config)'{-c,--config}'[Path to configuration file]:file:_files' \
|
||||||
|
'(-t --tag --filter-tag)'{-t,--tag,--filter-tag}'[Filter hosts by tag]:tag:' \
|
||||||
|
'(-g --group --category --filter-group)'{-g,--group,--category,--filter-group}'[Filter hosts by group or category]:group:' \
|
||||||
|
'(--source-type --filter-source --origin)'{--source-type,--filter-source,--origin}'[Filter hosts by source provider]:source:(proxmox static file plik k3s)' \
|
||||||
'(-V --version)'{-V,--version}'[Show program version and exit]' \
|
'(-V --version)'{-V,--version}'[Show program version and exit]' \
|
||||||
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,3 +19,9 @@
|
|||||||
- Consumers: Ansible (playbooks & Gitea Actions), linux-connector (fleet connection & runner).
|
- Consumers: Ansible (playbooks & Gitea Actions), linux-connector (fleet connection & runner).
|
||||||
- Key principle: Avoid overengineering. Read sources, merge & deduplicate in memory, emit clean inventory file.
|
- Key principle: Avoid overengineering. Read sources, merge & deduplicate in memory, emit clean inventory file.
|
||||||
- Remote repo: Public on Gitea (https://gitea.wired.synology.me/soda64/inventory-collector).
|
- Remote repo: Public on Gitea (https://gitea.wired.synology.me/soda64/inventory-collector).
|
||||||
|
- Release v1.1.0:
|
||||||
|
- Eliminated YAML anchors/aliases (&id/*id) across all YAML exporters with NoAliasDumper.
|
||||||
|
- Added wildcard DNS collision protection in ProxmoxCollector (NXDOMAIN probe detects catch-all wildcard IP like 192.168.5.70 and rejects false-positive fallback DNS matches).
|
||||||
|
- Added physical node interface querying (/nodes/{node}/network) for vmbr0 management IPs.
|
||||||
|
- Added CLI filtering: -t/--tag, -g/--group/--category, --source-type/--filter-source/--origin.
|
||||||
|
- Added automatic env file loading from ~/.config/inventory-collector/env, /etc/inventory-collector/env, and .env.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"""Universal homelab and fleet inventory collector and deduplicator."""
|
"""Universal homelab and fleet inventory collector and deduplicator."""
|
||||||
|
|
||||||
__version__ = "1.0.0"
|
__version__ = "1.1.0"
|
||||||
|
|
||||||
_yaml_warning_emitted = False
|
_yaml_warning_emitted = False
|
||||||
|
|
||||||
|
|||||||
@@ -86,11 +86,36 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="Synchronize inventory to both Ansible and linux-connector default paths."
|
help="Synchronize inventory to both Ansible and linux-connector default paths."
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-q", "--quiet",
|
||||||
|
action="store_true",
|
||||||
|
help="Silence all informational and warning messages on stderr."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-v", "--verbose",
|
||||||
|
action="store_true",
|
||||||
|
help="Enable verbose output (forces logs even in --list mode)."
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-c", "--config",
|
"-c", "--config",
|
||||||
type=Path,
|
type=Path,
|
||||||
help="Path to configuration file (config.yaml)."
|
help="Path to configuration file (config.yaml)."
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-t", "--tag", "--filter-tag",
|
||||||
|
dest="filter_tag",
|
||||||
|
help="Filter hosts by tag (e.g. 'hypervisor', 'pve', 'k3s')."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-g", "--group", "--category", "--filter-group",
|
||||||
|
dest="filter_group",
|
||||||
|
help="Filter hosts by group or category name (e.g. 'proxmox_vms', 'storage')."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--source-type", "--filter-source", "--origin",
|
||||||
|
dest="filter_source",
|
||||||
|
help="Filter hosts by source provider (e.g. 'proxmox', 'static', 'file', 'k3s')."
|
||||||
|
)
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
def main(argv: Optional[List[str]] = None) -> int:
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
@@ -127,15 +152,20 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
else:
|
else:
|
||||||
verify_ssl = app_config.proxmox.verify_ssl
|
verify_ssl = app_config.proxmox.verify_ssl
|
||||||
|
|
||||||
|
is_quiet = args.quiet or (args.list and not args.verbose)
|
||||||
|
|
||||||
if pve_url and pve_token_id and pve_token_secret:
|
if pve_url and pve_token_id and pve_token_secret:
|
||||||
sys.stderr.write(f"[INFO] Querying Proxmox VE API at {pve_url}...\n")
|
if not is_quiet:
|
||||||
|
sys.stderr.write(f"[INFO] Querying Proxmox VE API at {pve_url}...\n")
|
||||||
pve_collector = ProxmoxCollector(
|
pve_collector = ProxmoxCollector(
|
||||||
url=pve_url,
|
url=pve_url,
|
||||||
token_id=pve_token_id,
|
token_id=pve_token_id,
|
||||||
token_secret=pve_token_secret,
|
token_secret=pve_token_secret,
|
||||||
verify_ssl=verify_ssl,
|
verify_ssl=verify_ssl,
|
||||||
timeout=app_config.proxmox.timeout,
|
timeout=app_config.proxmox.timeout,
|
||||||
default_user=app_config.default_ssh_user
|
default_user=app_config.default_ssh_user,
|
||||||
|
quiet=is_quiet,
|
||||||
|
resolve_dns=app_config.proxmox.resolve_dns
|
||||||
)
|
)
|
||||||
raw_records.extend(pve_collector.collect())
|
raw_records.extend(pve_collector.collect())
|
||||||
|
|
||||||
@@ -162,12 +192,32 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
engine = DeduplicationEngine(conflict_policy=app_config.conflict_policy)
|
engine = DeduplicationEngine(conflict_policy=app_config.conflict_policy)
|
||||||
inv, warnings = engine.process(raw_records)
|
inv, warnings = engine.process(raw_records)
|
||||||
|
|
||||||
for w in warnings:
|
if not is_quiet:
|
||||||
sys.stderr.write(f"[WARN] {w}\n")
|
for w in warnings:
|
||||||
|
sys.stderr.write(f"[WARN] {w}\n")
|
||||||
|
|
||||||
|
# 4b. Filter inventory by tag, group, or source provider if requested
|
||||||
|
has_filter = bool(args.filter_tag or args.filter_group or args.filter_source)
|
||||||
|
if has_filter:
|
||||||
|
inv = inv.filter(
|
||||||
|
tag=args.filter_tag,
|
||||||
|
group=args.filter_group,
|
||||||
|
source=args.filter_source
|
||||||
|
)
|
||||||
|
|
||||||
# 5. Inspection / Dry-run Mode
|
# 5. Inspection / Dry-run Mode
|
||||||
if args.dry_run:
|
if args.dry_run:
|
||||||
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups.\n")
|
filter_desc = []
|
||||||
|
if args.filter_tag:
|
||||||
|
filter_desc.append(f"tag='{args.filter_tag}'")
|
||||||
|
if args.filter_group:
|
||||||
|
filter_desc.append(f"group='{args.filter_group}'")
|
||||||
|
if args.filter_source:
|
||||||
|
filter_desc.append(f"source='{args.filter_source}'")
|
||||||
|
filter_suffix = f" (filtered by {', '.join(filter_desc)})" if filter_desc else ""
|
||||||
|
|
||||||
|
if not is_quiet:
|
||||||
|
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups{filter_suffix}.\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)
|
||||||
@@ -185,10 +235,12 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
lc_dest = (app_config.output_linux_connector or Path("~/.config/linux-connector/hosts.yaml")).expanduser()
|
lc_dest = (app_config.output_linux_connector or Path("~/.config/linux-connector/hosts.yaml")).expanduser()
|
||||||
|
|
||||||
AnsibleYamlExporter().write_to_file(inv, ansible_dest)
|
AnsibleYamlExporter().write_to_file(inv, ansible_dest)
|
||||||
sys.stderr.write(f"[SUCCESS] Updated Ansible inventory: {ansible_dest}\n")
|
if not is_quiet:
|
||||||
|
sys.stderr.write(f"[SUCCESS] Updated Ansible inventory: {ansible_dest}\n")
|
||||||
|
|
||||||
LinuxConnectorExporter().write_to_file(inv, lc_dest)
|
LinuxConnectorExporter().write_to_file(inv, lc_dest)
|
||||||
sys.stderr.write(f"[SUCCESS] Updated linux-connector inventory: {lc_dest}\n")
|
if not is_quiet:
|
||||||
|
sys.stderr.write(f"[SUCCESS] Updated linux-connector inventory: {lc_dest}\n")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
# 8. Standard Format Export
|
# 8. Standard Format Export
|
||||||
@@ -204,7 +256,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
|
|
||||||
if args.output:
|
if args.output:
|
||||||
exporter.write_to_file(inv, args.output)
|
exporter.write_to_file(inv, args.output)
|
||||||
sys.stderr.write(f"[SUCCESS] Written {fmt} inventory to {args.output}\n")
|
if not is_quiet:
|
||||||
|
sys.stderr.write(f"[SUCCESS] Written {fmt} inventory to {args.output}\n")
|
||||||
else:
|
else:
|
||||||
sys.stdout.write(rendered)
|
sys.stdout.write(rendered)
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
token_secret: str,
|
token_secret: str,
|
||||||
verify_ssl: bool = False,
|
verify_ssl: bool = False,
|
||||||
timeout: int = 10,
|
timeout: int = 10,
|
||||||
default_user: str = "lain"
|
default_user: str = "lain",
|
||||||
|
quiet: bool = False,
|
||||||
|
resolve_dns: bool = True
|
||||||
) -> None:
|
) -> None:
|
||||||
# Normalize base URL (strip trailing slashes and /api2/json if included)
|
# Normalize base URL (strip trailing slashes and /api2/json if included)
|
||||||
clean_url = url.rstrip("/")
|
clean_url = url.rstrip("/")
|
||||||
@@ -30,6 +32,9 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
self.verify_ssl = verify_ssl
|
self.verify_ssl = verify_ssl
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
self.default_user = default_user
|
self.default_user = default_user
|
||||||
|
self.quiet = quiet
|
||||||
|
self.resolve_dns = resolve_dns
|
||||||
|
self.wildcard_ip: Optional[str] = self._detect_wildcard_dns() if self.resolve_dns else None
|
||||||
|
|
||||||
if not self.verify_ssl:
|
if not self.verify_ssl:
|
||||||
self.ssl_context = ssl._create_unverified_context()
|
self.ssl_context = ssl._create_unverified_context()
|
||||||
@@ -50,7 +55,8 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
# 500 often happens if guest agent is not running on VM
|
# 500 often happens if guest agent is not running on VM
|
||||||
return {}
|
return {}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
sys.stderr.write(f"[WARN] Proxmox API request failed for '{endpoint}': {e}\n")
|
if not self.quiet:
|
||||||
|
sys.stderr.write(f"[WARN] Proxmox API request failed for '{endpoint}': {e}\n")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def _parse_tags(self, raw_tags: Optional[str]) -> List[str]:
|
def _parse_tags(self, raw_tags: Optional[str]) -> List[str]:
|
||||||
@@ -59,12 +65,63 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
cleaned = re.sub(r"[,;]", " ", str(raw_tags))
|
cleaned = re.sub(r"[,;]", " ", str(raw_tags))
|
||||||
return [t.strip() for t in cleaned.split() if t.strip()]
|
return [t.strip() for t in cleaned.split() if t.strip()]
|
||||||
|
|
||||||
def _resolve_dns_ip(self, name: str) -> Optional[str]:
|
def _detect_wildcard_dns(self) -> Optional[str]:
|
||||||
|
"""Detect if local DNS environment resolves non-existent hostnames to a wildcard IP."""
|
||||||
try:
|
try:
|
||||||
return socket.gethostbyname(name)
|
import uuid
|
||||||
|
test_host = f"nxdomain-probe-{uuid.uuid4().hex[:12]}"
|
||||||
|
ip = socket.gethostbyname(test_host)
|
||||||
|
if ip and not self.quiet:
|
||||||
|
sys.stderr.write(f"[INFO] Detected DNS wildcard catch-all resolving to '{ip}'. Collision protection active.\n")
|
||||||
|
return ip
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def _resolve_dns_ip(self, name: str) -> Optional[str]:
|
||||||
|
if not self.resolve_dns:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
resolved = socket.gethostbyname(name)
|
||||||
|
if self.wildcard_ip and resolved == self.wildcard_ip:
|
||||||
|
# Wildcard catch-all detected; not a genuine host-specific resolution
|
||||||
|
return None
|
||||||
|
return resolved
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _resolve_node_ip(self, node_name: str, node_info: Dict[str, Any]) -> str:
|
||||||
|
# 1. From node info if present
|
||||||
|
if node_info.get("ip"):
|
||||||
|
return str(node_info["ip"])
|
||||||
|
|
||||||
|
# 2. Query /nodes/{node}/network for active physical bridge (vmbr0) or IP
|
||||||
|
net_data = self._api_get(f"/nodes/{node_name}/network")
|
||||||
|
if isinstance(net_data, list):
|
||||||
|
# Prefer vmbr0 or interface with gateway
|
||||||
|
for iface in net_data:
|
||||||
|
addr = iface.get("address")
|
||||||
|
if addr and not str(addr).startswith("127."):
|
||||||
|
if iface.get("iface") == "vmbr0" or iface.get("gateway"):
|
||||||
|
return str(addr)
|
||||||
|
for iface in net_data:
|
||||||
|
addr = iface.get("address")
|
||||||
|
if addr and not str(addr).startswith("127."):
|
||||||
|
return str(addr)
|
||||||
|
|
||||||
|
# 3. Safe DNS fallback
|
||||||
|
dns_ip = self._resolve_dns_ip(node_name)
|
||||||
|
if dns_ip:
|
||||||
|
return dns_ip
|
||||||
|
|
||||||
|
# 4. Fallback if base_url contains IP
|
||||||
|
m = re.search(r"://([^:/]+)", self.base_url)
|
||||||
|
if m:
|
||||||
|
host_part = m.group(1)
|
||||||
|
if re.match(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$", host_part):
|
||||||
|
return host_part
|
||||||
|
|
||||||
|
return ""
|
||||||
|
|
||||||
def _resolve_qemu_ip(self, node: str, vmid: int, vm_name: str) -> str:
|
def _resolve_qemu_ip(self, node: str, vmid: int, vm_name: str) -> str:
|
||||||
# 1. Try QEMU Guest Agent
|
# 1. Try QEMU Guest Agent
|
||||||
agent_data = self._api_get(f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces")
|
agent_data = self._api_get(f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces")
|
||||||
@@ -125,7 +182,7 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# Hypervisor physical node
|
# Hypervisor physical node
|
||||||
node_ip = node_info.get("ip") or self._resolve_dns_ip(node_name) or ""
|
node_ip = self._resolve_node_ip(node_name, node_info)
|
||||||
records.append(HostRecord(
|
records.append(HostRecord(
|
||||||
name=node_name,
|
name=node_name,
|
||||||
ansible_host=node_ip,
|
ansible_host=node_ip,
|
||||||
@@ -151,7 +208,8 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
ip = self._resolve_qemu_ip(node_name, vmid, vm_name)
|
ip = self._resolve_qemu_ip(node_name, vmid, vm_name)
|
||||||
if not ip:
|
if not ip:
|
||||||
tags.append("no-ip")
|
tags.append("no-ip")
|
||||||
sys.stderr.write(f"[WARN] No IP address discovered for VM '{vm_name}' (vmid: {vmid}, status: {status})\n")
|
if not self.quiet:
|
||||||
|
sys.stderr.write(f"[WARN] No IP address discovered for VM '{vm_name}' (vmid: {vmid}, status: {status})\n")
|
||||||
|
|
||||||
groups = ["proxmox_vms", f"pve_node_{node_name}", f"status_{status}"]
|
groups = ["proxmox_vms", f"pve_node_{node_name}", f"status_{status}"]
|
||||||
for t in tags:
|
for t in tags:
|
||||||
@@ -189,7 +247,8 @@ class ProxmoxCollector(BaseCollector):
|
|||||||
ip = self._resolve_lxc_ip(node_name, vmid, ct_name)
|
ip = self._resolve_lxc_ip(node_name, vmid, ct_name)
|
||||||
if not ip:
|
if not ip:
|
||||||
tags.append("no-ip")
|
tags.append("no-ip")
|
||||||
sys.stderr.write(f"[WARN] No IP address discovered for LXC container '{ct_name}' (vmid: {vmid}, status: {status})\n")
|
if not self.quiet:
|
||||||
|
sys.stderr.write(f"[WARN] No IP address discovered for LXC container '{ct_name}' (vmid: {vmid}, status: {status})\n")
|
||||||
|
|
||||||
groups = ["proxmox_lxc", f"pve_node_{node_name}", f"status_{status}"]
|
groups = ["proxmox_lxc", f"pve_node_{node_name}", f"status_{status}"]
|
||||||
for t in tags:
|
for t in tags:
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ class ProxmoxConfig:
|
|||||||
token_secret: str = ""
|
token_secret: str = ""
|
||||||
verify_ssl: bool = False
|
verify_ssl: bool = False
|
||||||
timeout: int = 10
|
timeout: int = 10
|
||||||
|
resolve_dns: bool = True
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class StaticFileConfig:
|
class StaticFileConfig:
|
||||||
@@ -104,8 +105,36 @@ class ConfigLoader:
|
|||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _load_env_files(cls) -> None:
|
||||||
|
"""Loads environment variables from standard env files if not already set in os.environ."""
|
||||||
|
candidates = [
|
||||||
|
Path("/etc/inventory-collector/env"),
|
||||||
|
Path("~/.config/inventory-collector/env").expanduser(),
|
||||||
|
Path("~/.config/inventory-collector/.env").expanduser(),
|
||||||
|
Path("./.env")
|
||||||
|
]
|
||||||
|
for path in candidates:
|
||||||
|
if path.is_file():
|
||||||
|
try:
|
||||||
|
for line in path.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
if line.startswith("export "):
|
||||||
|
line = line[7:].strip()
|
||||||
|
if "=" in line:
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
k = k.strip()
|
||||||
|
v = v.strip().strip("'\"")
|
||||||
|
if k and k not in os.environ:
|
||||||
|
os.environ[k] = v
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def load(cls, config_path: Optional[Path] = None) -> AppConfig:
|
def load(cls, config_path: Optional[Path] = None) -> AppConfig:
|
||||||
|
cls._load_env_files()
|
||||||
config = AppConfig()
|
config = AppConfig()
|
||||||
|
|
||||||
candidates: List[Path] = []
|
candidates: List[Path] = []
|
||||||
@@ -148,7 +177,8 @@ class ConfigLoader:
|
|||||||
token_id=str(pve_data.get("token_id", "")),
|
token_id=str(pve_data.get("token_id", "")),
|
||||||
token_secret=str(pve_data.get("token_secret", "")),
|
token_secret=str(pve_data.get("token_secret", "")),
|
||||||
verify_ssl=bool(pve_data.get("verify_ssl", False)),
|
verify_ssl=bool(pve_data.get("verify_ssl", False)),
|
||||||
timeout=int(pve_data.get("timeout", 10))
|
timeout=int(pve_data.get("timeout", 10)),
|
||||||
|
resolve_dns=bool(pve_data.get("resolve_dns", True))
|
||||||
)
|
)
|
||||||
|
|
||||||
# Parse sources.static_files
|
# Parse sources.static_files
|
||||||
|
|||||||
@@ -78,5 +78,8 @@ class AnsibleYamlExporter(BaseExporter):
|
|||||||
structure = self._build_structure(data)
|
structure = self._build_structure(data)
|
||||||
yaml = get_yaml_module()
|
yaml = get_yaml_module()
|
||||||
if yaml:
|
if yaml:
|
||||||
return yaml.dump(structure, sort_keys=False, default_flow_style=False)
|
class NoAliasDumper(yaml.SafeDumper):
|
||||||
|
def ignore_aliases(self, data):
|
||||||
|
return True
|
||||||
|
return yaml.dump(structure, Dumper=NoAliasDumper, sort_keys=False, default_flow_style=False)
|
||||||
return self._builtin_yaml_dump(structure) + "\n"
|
return self._builtin_yaml_dump(structure) + "\n"
|
||||||
@@ -68,5 +68,8 @@ class GenericYamlExporter(BaseExporter):
|
|||||||
structure = self._build_structure(data)
|
structure = self._build_structure(data)
|
||||||
yaml = get_yaml_module()
|
yaml = get_yaml_module()
|
||||||
if yaml:
|
if yaml:
|
||||||
return yaml.dump(structure, sort_keys=False, default_flow_style=False)
|
class NoAliasDumper(yaml.SafeDumper):
|
||||||
|
def ignore_aliases(self, data):
|
||||||
|
return True
|
||||||
|
return yaml.dump(structure, Dumper=NoAliasDumper, sort_keys=False, default_flow_style=False)
|
||||||
return self._builtin_yaml_dump(structure) + "\n"
|
return self._builtin_yaml_dump(structure) + "\n"
|
||||||
@@ -72,5 +72,8 @@ class LinuxConnectorExporter(BaseExporter):
|
|||||||
structure = self._build_structure(data)
|
structure = self._build_structure(data)
|
||||||
yaml = get_yaml_module()
|
yaml = get_yaml_module()
|
||||||
if yaml:
|
if yaml:
|
||||||
return yaml.dump(structure, sort_keys=False, default_flow_style=False)
|
class NoAliasDumper(yaml.SafeDumper):
|
||||||
|
def ignore_aliases(self, data):
|
||||||
|
return True
|
||||||
|
return yaml.dump(structure, Dumper=NoAliasDumper, sort_keys=False, default_flow_style=False)
|
||||||
return self._builtin_yaml_dump(structure) + "\n"
|
return self._builtin_yaml_dump(structure) + "\n"
|
||||||
@@ -33,3 +33,26 @@ class InventoryData:
|
|||||||
def get_hosts_by_group(self, group: str) -> List[HostRecord]:
|
def get_hosts_by_group(self, group: str) -> List[HostRecord]:
|
||||||
host_names = self.groups.get(group, [])
|
host_names = self.groups.get(group, [])
|
||||||
return [self.hosts[name] for name in host_names if name in self.hosts]
|
return [self.hosts[name] for name in host_names if name in self.hosts]
|
||||||
|
|
||||||
|
def filter(
|
||||||
|
self,
|
||||||
|
tag: Optional[str] = None,
|
||||||
|
group: Optional[str] = None,
|
||||||
|
source: Optional[str] = None
|
||||||
|
) -> "InventoryData":
|
||||||
|
filtered = InventoryData()
|
||||||
|
for host in self.hosts.values():
|
||||||
|
if tag and not any(tag.lower() == t.lower() for t in host.tags):
|
||||||
|
continue
|
||||||
|
if group and not any(group.lower() == g.lower() for g in host.groups):
|
||||||
|
continue
|
||||||
|
if source:
|
||||||
|
s_lower = source.lower()
|
||||||
|
if s_lower in ("file", "plik"):
|
||||||
|
match_source = "static" in host.source.lower()
|
||||||
|
else:
|
||||||
|
match_source = s_lower in host.source.lower()
|
||||||
|
if not match_source:
|
||||||
|
continue
|
||||||
|
filtered.add_host(host)
|
||||||
|
return filtered
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.0.0" "User Commands"
|
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.1.0" "User Commands"
|
||||||
.SH NAME
|
.SH NAME
|
||||||
inventory-collector \- Universal homelab and fleet inventory collector and deduplicator
|
inventory-collector \- Universal homelab and fleet inventory collector and deduplicator
|
||||||
.SH SYNOPSIS
|
.SH SYNOPSIS
|
||||||
@@ -19,11 +19,26 @@ Select output format: \fIansible-yaml\fR (default), \fIansible-json\fR, \fIlinux
|
|||||||
Inspect discovered hosts and groups in a formatted terminal table without writing or modifying any files.
|
Inspect discovered hosts and groups in a formatted terminal table without writing or modifying any files.
|
||||||
.TP
|
.TP
|
||||||
.B \-\-list
|
.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.
|
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. Stderr is quieted by default for clean Ansible execution.
|
||||||
.TP
|
.TP
|
||||||
.B \-\-sync
|
.B \-\-sync
|
||||||
Synchronize inventory simultaneously to both default Ansible and linux-connector destination paths.
|
Synchronize inventory simultaneously to both default Ansible and linux-connector destination paths.
|
||||||
.TP
|
.TP
|
||||||
|
.BR \-t ", " \-\-tag ", " \-\-filter\-tag " \fITAG\fR"
|
||||||
|
Filter inventory hosts by tag (e.g. \fIhypervisor\fR, \fIpve\fR, \fIk3s\fR).
|
||||||
|
.TP
|
||||||
|
.BR \-g ", " \-\-group ", " \-\-category ", " \-\-filter\-group " \fIGROUP\fR"
|
||||||
|
Filter inventory hosts by group or category name (e.g. \fIproxmox_vms\fR, \fIstorage\fR).
|
||||||
|
.TP
|
||||||
|
.BR \-\-source\-type ", " \-\-filter\-source ", " \-\-origin " \fISOURCE\fR"
|
||||||
|
Filter inventory hosts by source provider (e.g. \fIproxmox\fR, \fIstatic\fR, \fIfile\fR, \fIk3s\fR).
|
||||||
|
.TP
|
||||||
|
.BR \-q ", " \-\-quiet
|
||||||
|
Silence all informational and warning log messages on stderr.
|
||||||
|
.TP
|
||||||
|
.BR \-v ", " \-\-verbose
|
||||||
|
Enable verbose logging on stderr (forces output even in \fB\-\-list\fR mode).
|
||||||
|
.TP
|
||||||
.BR \-c ", " \-\-config " \fIFILE\fR"
|
.BR \-c ", " \-\-config " \fIFILE\fR"
|
||||||
Path to YAML configuration file. Defaults to \fI~/.config/inventory-collector/config.yaml\fR.
|
Path to YAML configuration file. Defaults to \fI~/.config/inventory-collector/config.yaml\fR.
|
||||||
.TP
|
.TP
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: inventory-collector
|
Name: inventory-collector
|
||||||
Version: 1.0.0
|
Version: 1.1.0
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: Universal homelab and fleet inventory collector and deduplicator
|
Summary: Universal homelab and fleet inventory collector and deduplicator
|
||||||
|
|
||||||
@@ -66,5 +66,16 @@ fi
|
|||||||
%doc %{_datadir}/doc/inventory-collector
|
%doc %{_datadir}/doc/inventory-collector
|
||||||
|
|
||||||
%changelog
|
%changelog
|
||||||
|
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.0-1
|
||||||
|
- Disable PyYAML anchors and aliases in YAML exporters for clean readability.
|
||||||
|
- Fix DNS wildcard collision false positives in Proxmox collector.
|
||||||
|
- Query Proxmox /nodes/{node}/network for physical node management IPs.
|
||||||
|
- Add filtering by tag (-t/--tag), group (-g/--group/--category), and source provider (--source-type/--filter-source/--origin).
|
||||||
|
- Auto-load environment variables from ~/.config/inventory-collector/env and /etc/inventory-collector/env.
|
||||||
|
|
||||||
|
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.0.1-1
|
||||||
|
- Silence info and warning stderr logs in --list dynamic inventory mode.
|
||||||
|
- Add -q/--quiet and -v/--verbose CLI flags.
|
||||||
|
|
||||||
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.0.0-1
|
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.0.0-1
|
||||||
- Initial release of inventory-collector.
|
- Initial release of inventory-collector.
|
||||||
@@ -36,6 +36,21 @@ class TestCliIntegration(unittest.TestCase):
|
|||||||
parsed = json.loads(stdout_capture.getvalue())
|
parsed = json.loads(stdout_capture.getvalue())
|
||||||
self.assertIn("_meta", parsed)
|
self.assertIn("_meta", parsed)
|
||||||
self.assertIn("hostvars", parsed["_meta"])
|
self.assertIn("hostvars", parsed["_meta"])
|
||||||
|
self.assertEqual(stderr_capture.getvalue(), "")
|
||||||
|
finally:
|
||||||
|
sys.stdout = old_stdout
|
||||||
|
sys.stderr = old_stderr
|
||||||
|
|
||||||
|
def test_cli_quiet_and_verbose(self):
|
||||||
|
stdout_capture = StringIO()
|
||||||
|
stderr_capture = StringIO()
|
||||||
|
old_stdout, old_stderr = sys.stdout, sys.stderr
|
||||||
|
try:
|
||||||
|
sys.stdout = stdout_capture
|
||||||
|
sys.stderr = stderr_capture
|
||||||
|
code = main(["--check", "-q"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(stderr_capture.getvalue(), "")
|
||||||
finally:
|
finally:
|
||||||
sys.stdout = old_stdout
|
sys.stdout = old_stdout
|
||||||
sys.stderr = old_stderr
|
sys.stderr = old_stderr
|
||||||
@@ -59,5 +74,44 @@ class TestCliIntegration(unittest.TestCase):
|
|||||||
content = target_ini.read_text(encoding="utf-8")
|
content = target_ini.read_text(encoding="utf-8")
|
||||||
self.assertIn("ansible_host=", content)
|
self.assertIn("ansible_host=", content)
|
||||||
|
|
||||||
|
def test_cli_filtering_by_tag(self):
|
||||||
|
stdout_capture = StringIO()
|
||||||
|
old_stdout = sys.stdout
|
||||||
|
try:
|
||||||
|
sys.stdout = stdout_capture
|
||||||
|
code = main(["--check", "-q", "-t", "hypervisor"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
out = stdout_capture.getvalue()
|
||||||
|
self.assertIn("node0", out)
|
||||||
|
self.assertNotIn("k3s-master-0", out)
|
||||||
|
finally:
|
||||||
|
sys.stdout = old_stdout
|
||||||
|
|
||||||
|
def test_cli_filtering_by_group(self):
|
||||||
|
stdout_capture = StringIO()
|
||||||
|
old_stdout = sys.stdout
|
||||||
|
try:
|
||||||
|
sys.stdout = stdout_capture
|
||||||
|
code = main(["--check", "-q", "-g", "k3s_master"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
out = stdout_capture.getvalue()
|
||||||
|
self.assertIn("k3s-master-0", out)
|
||||||
|
self.assertNotIn("node0", out)
|
||||||
|
finally:
|
||||||
|
sys.stdout = old_stdout
|
||||||
|
|
||||||
|
def test_cli_filtering_by_source(self):
|
||||||
|
stdout_capture = StringIO()
|
||||||
|
old_stdout = sys.stdout
|
||||||
|
try:
|
||||||
|
sys.stdout = stdout_capture
|
||||||
|
code = main(["--check", "-q", "--source-type", "tracer"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
out = stdout_capture.getvalue()
|
||||||
|
self.assertIn("k3s-master-0", out)
|
||||||
|
self.assertIn("node0", out)
|
||||||
|
finally:
|
||||||
|
sys.stdout = old_stdout
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -47,5 +47,21 @@ destinations:
|
|||||||
finally:
|
finally:
|
||||||
cfg_path.unlink()
|
cfg_path.unlink()
|
||||||
|
|
||||||
|
def test_load_env_files(self):
|
||||||
|
with NamedTemporaryFile("w+", suffix=".env", delete=False) as f:
|
||||||
|
f.write("TEST_ENV_VAR_COLLECTOR=dynamic_val\nexport TEST_ANOTHER=exported_val\n")
|
||||||
|
env_file = Path(f.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Test direct parsing through _load_env_files candidate injection
|
||||||
|
with unittest.mock.patch("inventory_collector.config.Path.is_file") as mock_is_file, \
|
||||||
|
unittest.mock.patch("inventory_collector.config.Path.read_text") as mock_read:
|
||||||
|
mock_is_file.return_value = True
|
||||||
|
mock_read.return_value = "TEST_AUTO_LOADED_KEY=success_val\n"
|
||||||
|
ConfigLoader._load_env_files()
|
||||||
|
self.assertEqual(os.environ.get("TEST_AUTO_LOADED_KEY"), "success_val")
|
||||||
|
finally:
|
||||||
|
env_file.unlink()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -73,5 +73,16 @@ class TestExtendedExporters(unittest.TestCase):
|
|||||||
self.assertIn("[proxmox_nodes]", output)
|
self.assertIn("[proxmox_nodes]", output)
|
||||||
self.assertIn("node0 ansible_host=192.168.0.101 ansible_user=root", output)
|
self.assertIn("node0 ansible_host=192.168.0.101 ansible_user=root", output)
|
||||||
|
|
||||||
|
def test_yaml_exporters_no_anchors_or_aliases(self):
|
||||||
|
from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter
|
||||||
|
# Create inventory where multiple groups contain the exact same host
|
||||||
|
ansible_out = AnsibleYamlExporter().export(self.inv)
|
||||||
|
lc_out = LinuxConnectorExporter().export(self.inv)
|
||||||
|
gen_out = GenericYamlExporter().export(self.inv)
|
||||||
|
|
||||||
|
for out in (ansible_out, lc_out, gen_out):
|
||||||
|
self.assertNotIn("&id", out, "Found YAML anchor &id in output")
|
||||||
|
self.assertNotIn("*id", out, "Found YAML alias *id in output")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -33,13 +33,13 @@ class TestPackaging(unittest.TestCase):
|
|||||||
|
|
||||||
def test_get_version(self):
|
def test_get_version(self):
|
||||||
version = get_version(self.source_root)
|
version = get_version(self.source_root)
|
||||||
self.assertEqual(version, "1.0.0")
|
self.assertEqual(version, "1.1.0")
|
||||||
|
|
||||||
def test_build_tarball(self):
|
def test_build_tarball(self):
|
||||||
builder = PackageBuilder(
|
builder = PackageBuilder(
|
||||||
source_root=self.source_root,
|
source_root=self.source_root,
|
||||||
output_dir=self.output_dir,
|
output_dir=self.output_dir,
|
||||||
version="1.0.0",
|
version="1.1.0",
|
||||||
)
|
)
|
||||||
tar_path = builder.build_tarball()
|
tar_path = builder.build_tarball()
|
||||||
self.assertTrue(tar_path.exists())
|
self.assertTrue(tar_path.exists())
|
||||||
@@ -48,16 +48,16 @@ class TestPackaging(unittest.TestCase):
|
|||||||
# Verify tar contents
|
# Verify tar contents
|
||||||
with tarfile.open(str(tar_path), "r:gz") as tar:
|
with tarfile.open(str(tar_path), "r:gz") as tar:
|
||||||
names = tar.getnames()
|
names = tar.getnames()
|
||||||
self.assertIn("inventory-collector-1.0.0/bin/inventory-collector", names)
|
self.assertIn("inventory-collector-1.1.0/bin/inventory-collector", names)
|
||||||
self.assertIn("inventory-collector-1.0.0/inventory_collector/__init__.py", names)
|
self.assertIn("inventory-collector-1.1.0/inventory_collector/__init__.py", names)
|
||||||
self.assertIn("inventory-collector-1.0.0/install.sh", names)
|
self.assertIn("inventory-collector-1.1.0/install.sh", names)
|
||||||
self.assertIn("inventory-collector-1.0.0/packaging/install.sh", names)
|
self.assertIn("inventory-collector-1.1.0/packaging/install.sh", names)
|
||||||
|
|
||||||
def test_build_deb(self):
|
def test_build_deb(self):
|
||||||
builder = PackageBuilder(
|
builder = PackageBuilder(
|
||||||
source_root=self.source_root,
|
source_root=self.source_root,
|
||||||
output_dir=self.output_dir,
|
output_dir=self.output_dir,
|
||||||
version="1.0.0",
|
version="1.1.0",
|
||||||
)
|
)
|
||||||
deb_path = builder.build_deb()
|
deb_path = builder.build_deb()
|
||||||
self.assertTrue(deb_path.exists())
|
self.assertTrue(deb_path.exists())
|
||||||
|
|||||||
@@ -121,5 +121,48 @@ class TestProxmoxCollector(unittest.TestCase):
|
|||||||
self.assertIn("proxmox_lxc", pihole.groups)
|
self.assertIn("proxmox_lxc", pihole.groups)
|
||||||
self.assertIn("dns", pihole.groups)
|
self.assertIn("dns", pihole.groups)
|
||||||
|
|
||||||
|
@patch("inventory_collector.collectors.proxmox.socket.gethostbyname")
|
||||||
|
def test_wildcard_dns_collision_protection(self, mock_gethostbyname):
|
||||||
|
# Simulate wildcard DNS where ANY domain resolves to 192.168.5.70
|
||||||
|
mock_gethostbyname.return_value = "192.168.5.70"
|
||||||
|
|
||||||
|
collector = ProxmoxCollector(
|
||||||
|
url="https://pve-01.wired.intra:8006",
|
||||||
|
token_id="root@pam!collector",
|
||||||
|
token_secret="test-secret",
|
||||||
|
quiet=True,
|
||||||
|
resolve_dns=True
|
||||||
|
)
|
||||||
|
# Wildcard detection should have recorded the catch-all IP
|
||||||
|
self.assertEqual(collector.wildcard_ip, "192.168.5.70")
|
||||||
|
|
||||||
|
# Resolving an unknown VM name (like winxp) should be rejected (return None)
|
||||||
|
resolved = collector._resolve_dns_ip("winxp")
|
||||||
|
self.assertIsNone(resolved)
|
||||||
|
|
||||||
|
@patch("inventory_collector.collectors.proxmox.urllib.request.urlopen")
|
||||||
|
def test_node_ip_resolution_from_network(self, mock_urlopen):
|
||||||
|
resp = MagicMock()
|
||||||
|
resp.status = 200
|
||||||
|
resp.__enter__.return_value = resp
|
||||||
|
import json
|
||||||
|
resp.read.return_value = json.dumps({
|
||||||
|
"data": [
|
||||||
|
{"iface": "lo", "address": "127.0.0.1"},
|
||||||
|
{"iface": "vmbr0", "address": "192.168.0.101", "gateway": "192.168.0.2"}
|
||||||
|
]
|
||||||
|
}).encode("utf-8")
|
||||||
|
mock_urlopen.return_value = resp
|
||||||
|
|
||||||
|
collector = ProxmoxCollector(
|
||||||
|
url="https://pve-01.wired.intra:8006",
|
||||||
|
token_id="root@pam!collector",
|
||||||
|
token_secret="test-secret",
|
||||||
|
quiet=True,
|
||||||
|
resolve_dns=False
|
||||||
|
)
|
||||||
|
node_ip = collector._resolve_node_ip("node0", {})
|
||||||
|
self.assertEqual(node_ip, "192.168.0.101")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user