feat: release v1.1.0 - clean YAML, wildcard DNS protection, and tag/group/source filtering
Build and Publish Release / Build Packages and Publish (push) Successful in 9s
Build and Publish Release / Build Packages and Publish (push) Successful in 9s
This commit is contained in:
1 parent
5fedc44c6b
commit
598e5d7397
18 files changed
+318
-22
No files matched your search
@@ -1,6 +1,6 @@
|
||||
"""Universal homelab and fleet inventory collector and deduplicator."""
|
||||
|
||||
__version__ = "1.0.1"
|
||||
__version__ = "1.1.0"
|
||||
|
||||
_yaml_warning_emitted = False
|
||||
|
||||
|
||||
@@ -101,6 +101,21 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
type=Path,
|
||||
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
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
@@ -149,7 +164,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
verify_ssl=verify_ssl,
|
||||
timeout=app_config.proxmox.timeout,
|
||||
default_user=app_config.default_ssh_user,
|
||||
quiet=is_quiet
|
||||
quiet=is_quiet,
|
||||
resolve_dns=app_config.proxmox.resolve_dns
|
||||
)
|
||||
raw_records.extend(pve_collector.collect())
|
||||
|
||||
@@ -180,10 +196,28 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
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
|
||||
if args.dry_run:
|
||||
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.\n")
|
||||
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups{filter_suffix}.\n")
|
||||
print("NAME IP ADDRESS SOURCE GROUPS")
|
||||
for h in inv.hosts.values():
|
||||
groups_str = ", ".join(h.groups)
|
||||
|
||||
@@ -20,7 +20,8 @@ class ProxmoxCollector(BaseCollector):
|
||||
verify_ssl: bool = False,
|
||||
timeout: int = 10,
|
||||
default_user: str = "lain",
|
||||
quiet: bool = False
|
||||
quiet: bool = False,
|
||||
resolve_dns: bool = True
|
||||
) -> None:
|
||||
# Normalize base URL (strip trailing slashes and /api2/json if included)
|
||||
clean_url = url.rstrip("/")
|
||||
@@ -32,6 +33,8 @@ class ProxmoxCollector(BaseCollector):
|
||||
self.timeout = timeout
|
||||
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:
|
||||
self.ssl_context = ssl._create_unverified_context()
|
||||
@@ -62,12 +65,63 @@ class ProxmoxCollector(BaseCollector):
|
||||
cleaned = re.sub(r"[,;]", " ", str(raw_tags))
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
# 1. Try QEMU Guest Agent
|
||||
agent_data = self._api_get(f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces")
|
||||
@@ -128,7 +182,7 @@ class ProxmoxCollector(BaseCollector):
|
||||
continue
|
||||
|
||||
# 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(
|
||||
name=node_name,
|
||||
ansible_host=node_ip,
|
||||
|
||||
@@ -13,6 +13,7 @@ class ProxmoxConfig:
|
||||
token_secret: str = ""
|
||||
verify_ssl: bool = False
|
||||
timeout: int = 10
|
||||
resolve_dns: bool = True
|
||||
|
||||
@dataclass
|
||||
class StaticFileConfig:
|
||||
@@ -104,8 +105,36 @@ class ConfigLoader:
|
||||
|
||||
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
|
||||
def load(cls, config_path: Optional[Path] = None) -> AppConfig:
|
||||
cls._load_env_files()
|
||||
config = AppConfig()
|
||||
|
||||
candidates: List[Path] = []
|
||||
@@ -148,7 +177,8 @@ class ConfigLoader:
|
||||
token_id=str(pve_data.get("token_id", "")),
|
||||
token_secret=str(pve_data.get("token_secret", "")),
|
||||
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
|
||||
|
||||
@@ -78,5 +78,8 @@ class AnsibleYamlExporter(BaseExporter):
|
||||
structure = self._build_structure(data)
|
||||
yaml = get_yaml_module()
|
||||
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"
|
||||
@@ -68,5 +68,8 @@ class GenericYamlExporter(BaseExporter):
|
||||
structure = self._build_structure(data)
|
||||
yaml = get_yaml_module()
|
||||
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"
|
||||
@@ -72,5 +72,8 @@ class LinuxConnectorExporter(BaseExporter):
|
||||
structure = self._build_structure(data)
|
||||
yaml = get_yaml_module()
|
||||
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"
|
||||
@@ -33,3 +33,26 @@ class InventoryData:
|
||||
def get_hosts_by_group(self, group: str) -> List[HostRecord]:
|
||||
host_names = self.groups.get(group, [])
|
||||
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
|
||||
Reference in new issue
Block a user