feat(slice-6): implement config loader, CLI check mode, comprehensive documentation, and shell completions
This commit is contained in:
1 parent
869fd241e7
commit
e5784db650
9 files changed
+616
-29
No files matched your search
+33
-15
@@ -97,19 +97,35 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
from inventory_collector.config import ConfigLoader
|
||||
app_config = ConfigLoader.load(args.config)
|
||||
|
||||
raw_records: List[HostRecord] = []
|
||||
|
||||
# 1. Load from static sources if specified
|
||||
if args.sources:
|
||||
for src in args.sources:
|
||||
collector = StaticFileCollector(src)
|
||||
raw_records.extend(collector.collect())
|
||||
# 1. Load from static sources (CLI arguments take precedence, then config files)
|
||||
sources = list(args.sources or [])
|
||||
if not sources and app_config.static_files:
|
||||
for sf in app_config.static_files:
|
||||
sources.append(sf.path)
|
||||
|
||||
# 2. Check for Proxmox environment variables
|
||||
pve_url = os.getenv("PROXMOX_URL") or os.getenv("ANSIBLE_PROXMOX_URL")
|
||||
pve_token_id = os.getenv("PROXMOX_TOKEN_ID") or os.getenv("ANSIBLE_PROXMOX_TOKEN_ID")
|
||||
pve_token_secret = os.getenv("PROXMOX_TOKEN_SECRET") or os.getenv("ANSIBLE_PROXMOX_TOKEN_SECRET")
|
||||
verify_ssl = os.getenv("PROXMOX_VERIFY_SSL", "false").lower() in ("true", "1", "yes")
|
||||
for src in sources:
|
||||
collector = StaticFileCollector(
|
||||
src,
|
||||
default_user=app_config.default_ssh_user,
|
||||
default_port=app_config.default_ssh_port
|
||||
)
|
||||
raw_records.extend(collector.collect())
|
||||
|
||||
# 2. Check for Proxmox credentials (env vars take precedence, then config)
|
||||
pve_url = os.getenv("PROXMOX_URL") or os.getenv("ANSIBLE_PROXMOX_URL") or (app_config.proxmox.url if app_config.proxmox.enabled else "")
|
||||
pve_token_id = os.getenv("PROXMOX_TOKEN_ID") or os.getenv("ANSIBLE_PROXMOX_TOKEN_ID") or app_config.proxmox.token_id
|
||||
pve_token_secret = os.getenv("PROXMOX_TOKEN_SECRET") or os.getenv("ANSIBLE_PROXMOX_TOKEN_SECRET") or app_config.proxmox.token_secret
|
||||
|
||||
verify_ssl_env = os.getenv("PROXMOX_VERIFY_SSL")
|
||||
if verify_ssl_env is not None:
|
||||
verify_ssl = verify_ssl_env.lower() in ("true", "1", "yes")
|
||||
else:
|
||||
verify_ssl = app_config.proxmox.verify_ssl
|
||||
|
||||
if pve_url and pve_token_id and pve_token_secret:
|
||||
sys.stderr.write(f"[INFO] Querying Proxmox VE API at {pve_url}...\n")
|
||||
@@ -117,7 +133,9 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
url=pve_url,
|
||||
token_id=pve_token_id,
|
||||
token_secret=pve_token_secret,
|
||||
verify_ssl=verify_ssl
|
||||
verify_ssl=verify_ssl,
|
||||
timeout=app_config.proxmox.timeout,
|
||||
default_user=app_config.default_ssh_user
|
||||
)
|
||||
raw_records.extend(pve_collector.collect())
|
||||
|
||||
@@ -126,7 +144,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
raw_records.append(HostRecord(
|
||||
name="k3s-master-0",
|
||||
ansible_host="192.168.5.70",
|
||||
ansible_user="lain",
|
||||
ansible_user=app_config.default_ssh_user,
|
||||
groups=["k3s_master", "k3s_cluster"],
|
||||
tags=["control-plane", "proxmox"],
|
||||
source="tracer"
|
||||
@@ -141,7 +159,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
))
|
||||
|
||||
# 4. Deduplicate and merge records in memory
|
||||
engine = DeduplicationEngine()
|
||||
engine = DeduplicationEngine(conflict_policy=app_config.conflict_policy)
|
||||
inv, warnings = engine.process(raw_records)
|
||||
|
||||
for w in warnings:
|
||||
@@ -163,8 +181,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
# 7. Simultaneous Synchronization Mode (--sync)
|
||||
if args.sync:
|
||||
ansible_dest = Path("inventory/hosts.yaml")
|
||||
lc_dest = Path("~/.config/linux-connector/hosts.yaml").expanduser()
|
||||
ansible_dest = app_config.output_ansible or Path("inventory/hosts.yaml")
|
||||
lc_dest = (app_config.output_linux_connector or Path("~/.config/linux-connector/hosts.yaml")).expanduser()
|
||||
|
||||
AnsibleYamlExporter().write_to_file(inv, ansible_dest)
|
||||
sys.stderr.write(f"[SUCCESS] Updated Ansible inventory: {ansible_dest}\n")
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from inventory_collector import get_yaml_module
|
||||
|
||||
@dataclass
|
||||
class ProxmoxConfig:
|
||||
enabled: bool = False
|
||||
url: str = ""
|
||||
token_id: str = ""
|
||||
token_secret: str = ""
|
||||
verify_ssl: bool = False
|
||||
timeout: int = 10
|
||||
|
||||
@dataclass
|
||||
class StaticFileConfig:
|
||||
path: Path
|
||||
required: bool = False
|
||||
|
||||
@dataclass
|
||||
class AppConfig:
|
||||
proxmox: ProxmoxConfig = field(default_factory=ProxmoxConfig)
|
||||
static_files: List[StaticFileConfig] = field(default_factory=list)
|
||||
default_ssh_user: str = "lain"
|
||||
default_ssh_port: int = 22
|
||||
conflict_policy: str = "runtime_over_static"
|
||||
output_ansible: Optional[Path] = None
|
||||
output_linux_connector: Optional[Path] = None
|
||||
output_yaml: Optional[Path] = None
|
||||
output_xml: Optional[Path] = None
|
||||
|
||||
class ConfigLoader:
|
||||
"""Loads configuration with environment variable interpolation."""
|
||||
|
||||
@staticmethod
|
||||
def resolve_env_vars(raw: str) -> str:
|
||||
def repl(match):
|
||||
var_name = match.group(1) or match.group(2)
|
||||
return os.environ.get(var_name, "")
|
||||
return re.sub(r"\$\{([A-Za-z0-9_]+)\}|\$([A-Za-z0-9_]+)", repl, raw)
|
||||
|
||||
@classmethod
|
||||
def _parse_yaml_fallback(cls, content: str) -> Dict[str, Any]:
|
||||
"""Simple fallback parser for configuration files when PyYAML is not present."""
|
||||
data: Dict[str, Any] = {}
|
||||
# stack items: (indent_level, container_dict_or_list, key_in_parent)
|
||||
stack: List[Tuple[int, Any, Optional[str]]] = [(-1, data, 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(" "))
|
||||
|
||||
# Pop stack for shallower or same indent
|
||||
while len(stack) > 1 and indent <= stack[-1][0]:
|
||||
stack.pop()
|
||||
|
||||
parent_indent, parent_obj, parent_key = stack[-1]
|
||||
|
||||
if stripped.startswith("-"):
|
||||
# It's a list item. If parent_obj was an empty dict mapped to parent_key, turn it into list!
|
||||
grandparent = stack[-2][1] if len(stack) > 1 else None
|
||||
if isinstance(parent_obj, dict) and not parent_obj and grandparent and parent_key:
|
||||
new_list: List[Any] = []
|
||||
grandparent[parent_key] = new_list
|
||||
stack[-1] = (parent_indent, new_list, parent_key)
|
||||
parent_obj = new_list
|
||||
|
||||
target_list = parent_obj if isinstance(parent_obj, list) else []
|
||||
|
||||
item_content = stripped[1:].strip()
|
||||
if ":" in item_content:
|
||||
k, v = item_content.split(":", 1)
|
||||
k = k.strip()
|
||||
v = v.strip().strip("'\"")
|
||||
val = True if v.lower() == "true" else (False if v.lower() == "false" else (int(v) if v.isdigit() else v))
|
||||
new_dict = {k: val}
|
||||
target_list.append(new_dict)
|
||||
stack.append((indent, new_dict, k))
|
||||
else:
|
||||
target_list.append(item_content.strip("'\""))
|
||||
continue
|
||||
|
||||
if ":" in stripped:
|
||||
k, v = stripped.split(":", 1)
|
||||
k = k.strip()
|
||||
v = v.strip().strip("'\"")
|
||||
|
||||
if not v:
|
||||
# New sub-container
|
||||
new_sub: Dict[str, Any] = {}
|
||||
if isinstance(parent_obj, dict):
|
||||
parent_obj[k] = new_sub
|
||||
stack.append((indent, new_sub, k))
|
||||
else:
|
||||
val = True if v.lower() == "true" else (False if v.lower() == "false" else (int(v) if v.isdigit() else v))
|
||||
if isinstance(parent_obj, dict):
|
||||
parent_obj[k] = val
|
||||
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def load(cls, config_path: Optional[Path] = None) -> AppConfig:
|
||||
config = AppConfig()
|
||||
|
||||
candidates: List[Path] = []
|
||||
if config_path:
|
||||
candidates.append(Path(config_path).expanduser().resolve())
|
||||
else:
|
||||
candidates.extend([
|
||||
Path("./inventory-collector.yaml").resolve(),
|
||||
Path("./inventory-collector.yml").resolve(),
|
||||
Path("~/.config/inventory-collector/config.yaml").expanduser().resolve(),
|
||||
Path("/etc/inventory-collector/config.yaml")
|
||||
])
|
||||
|
||||
found_path: Optional[Path] = None
|
||||
for cand in candidates:
|
||||
if cand.is_file():
|
||||
found_path = cand
|
||||
break
|
||||
|
||||
if not found_path:
|
||||
return config
|
||||
|
||||
content = found_path.read_text(encoding="utf-8")
|
||||
interpolated = cls.resolve_env_vars(content)
|
||||
|
||||
yaml = get_yaml_module()
|
||||
data: Dict[str, Any] = {}
|
||||
if yaml:
|
||||
data = yaml.safe_load(interpolated) or {}
|
||||
else:
|
||||
data = cls._parse_yaml_fallback(interpolated)
|
||||
|
||||
# Parse sources.proxmox
|
||||
sources = data.get("sources", {})
|
||||
pve_data = sources.get("proxmox", {})
|
||||
if pve_data:
|
||||
config.proxmox = ProxmoxConfig(
|
||||
enabled=bool(pve_data.get("enabled", True)),
|
||||
url=str(pve_data.get("url", "")),
|
||||
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))
|
||||
)
|
||||
|
||||
# Parse sources.static_files
|
||||
for sf in sources.get("static_files", []):
|
||||
if isinstance(sf, dict) and "path" in sf:
|
||||
config.static_files.append(StaticFileConfig(
|
||||
path=Path(sf["path"]),
|
||||
required=bool(sf.get("required", False))
|
||||
))
|
||||
elif isinstance(sf, str):
|
||||
config.static_files.append(StaticFileConfig(path=Path(sf)))
|
||||
|
||||
# Parse defaults
|
||||
defaults = data.get("defaults", {})
|
||||
if defaults:
|
||||
config.default_ssh_user = defaults.get("ssh_user", config.default_ssh_user)
|
||||
config.default_ssh_port = int(defaults.get("ssh_port", config.default_ssh_port))
|
||||
config.conflict_policy = defaults.get("conflict_policy", config.conflict_policy)
|
||||
|
||||
# Parse destinations
|
||||
destinations = data.get("destinations", {})
|
||||
if destinations:
|
||||
if "ansible" in destinations:
|
||||
config.output_ansible = Path(destinations["ansible"])
|
||||
if "linux_connector" in destinations:
|
||||
config.output_linux_connector = Path(destinations["linux_connector"])
|
||||
if "yaml" in destinations:
|
||||
config.output_yaml = Path(destinations["yaml"])
|
||||
if "xml" in destinations:
|
||||
config.output_xml = Path(destinations["xml"])
|
||||
|
||||
return config
|
||||
Reference in new issue
Block a user