Files
soda64 1dbbb1ce56
Build and Publish Release / Build Packages and Publish (push) Successful in 10s
feat: release v1.1.2 - hardened IP sorting with ipaddress and config sort defaults
2026-10-03 22:18:10 +02:00

91 lines
3.3 KiB
Python

import ipaddress
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
@dataclass(frozen=True)
class HostRecord:
name: str
ansible_host: str
ansible_user: str = "lain"
ansible_port: int = 22
ansible_ssh_private_key_file: Optional[str] = None
groups: List[str] = field(default_factory=list)
tags: List[str] = field(default_factory=list)
description: str = ""
variables: Dict[str, Any] = field(default_factory=dict)
source: str = "unknown"
@dataclass
class InventoryData:
hosts: Dict[str, HostRecord] = field(default_factory=dict)
groups: Dict[str, List[str]] = field(default_factory=dict)
def add_host(self, host: HostRecord) -> None:
self.hosts[host.name] = host
for group in host.groups:
if group not in self.groups:
self.groups[group] = []
if host.name not in self.groups[group]:
self.groups[group].append(host.name)
def get_host(self, name: str) -> Optional[HostRecord]:
return self.hosts.get(name)
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
def sort(self, sort_by: str = "name", reverse: bool = False) -> "InventoryData":
sorted_inv = InventoryData()
def ip_sort_key(ip: str):
clean_ip = (ip or "").strip()
if not clean_ip:
return (2, 0, "")
# Strip single port if present e.g. 192.168.1.1:22
if ":" in clean_ip and not clean_ip.startswith("[") and clean_ip.count(":") == 1:
clean_ip = clean_ip.split(":")[0]
# Strip CIDR prefix if present e.g. 192.168.1.1/24
if "/" in clean_ip:
clean_ip = clean_ip.split("/")[0]
try:
addr = ipaddress.ip_address(clean_ip)
return (0, addr.version, int(addr))
except Exception:
return (1, 0, clean_ip.lower())
def record_key(host: HostRecord):
if sort_by.lower() == "ip":
return (ip_sort_key(host.ansible_host), host.name.lower())
return (host.name.lower(), ip_sort_key(host.ansible_host))
sorted_records = sorted(self.hosts.values(), key=record_key, reverse=reverse)
for host in sorted_records:
sorted_inv.add_host(host)
return sorted_inv