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
+615
-28
No files matched your search
@@ -1,22 +1,103 @@
|
||||
# Inventory Collector (`inventory-collector`)
|
||||
|
||||
Universal homelab and fleet inventory collector and deduplicator for Ansible and `linux-connector`.
|
||||
Universal homelab and fleet inventory collector and deduplicator for **Ansible** and **`linux-connector`**.
|
||||
|
||||
## Overview
|
||||
---
|
||||
|
||||
`inventory-collector` queries infrastructure sources (Proxmox VE REST API, static YAML/INI files), normalizes and deduplicates host records in memory, and generates unified inventory files for:
|
||||
- **Ansible:** Playbook execution (`-i hosts.yaml`) and dynamic inventory mode (`--list`).
|
||||
- **`linux-connector`:** Interactive TUI fuzzy launcher and fleet command runner (`hosts.yaml`).
|
||||
- **Standard Exports:** Clean generic YAML and formatted XML for external tooling and CMDBs.
|
||||
## Features
|
||||
|
||||
## Architecture & Plans
|
||||
- **Multi-Source Discovery:** Gathers physical hosts, virtual machines, and LXC containers dynamically from Proxmox VE REST API, alongside static Ansible INI and YAML files.
|
||||
- **In-Memory Deduplication:** Automatically merges host records across sources, calculates group and tag unions, and flags IP/user conflicts on `stderr`.
|
||||
- **4-Tier IP Resolution:** QEMU Guest Agent $\rightarrow$ PVE hardware config (`ipconfig0`) $\rightarrow$ Static definitions $\rightarrow$ Local DNS resolution.
|
||||
- **Multi-Format Exporters:**
|
||||
- `ansible-yaml`: Native Ansible YAML inventory (`all.children`).
|
||||
- `ansible-json`: Executable Ansible Dynamic Inventory script format (`--list` with `_meta.hostvars`).
|
||||
- `linux-connector`: Native `hosts.yaml` for instant pairing with `linux-connector`.
|
||||
- `yaml`: Clean, generic YAML dictionary.
|
||||
- `xml`: Well-formed, pretty-printed XML for CMDB and enterprise monitoring tools.
|
||||
- `ini`: Standard Ansible INI inventory sections.
|
||||
- **Simultaneous Target Sync (`--sync`):** Synchronizes both Ansible and `linux-connector` inventories with one command.
|
||||
- **Zero-Secrets Policy:** Credentials read from environment variables (`PROXMOX_*`, `ANSIBLE_PROXMOX_*`) or configuration files with variable interpolation.
|
||||
- **Lean Runtime:** Pure Python 3 standard library with only a single dependency (`PyYAML`).
|
||||
|
||||
The project follows the Software Factory 4-Gate Workflow:
|
||||
- [00-status.md](docs/plans/inventory-collector/00-status.md) — Implementation status and slice progress.
|
||||
- [01-spec.md](docs/plans/inventory-collector/01-spec.md) — Product specification and CLI interfaces.
|
||||
- [02-architecture.md](docs/plans/inventory-collector/02-architecture.md) — Technical architecture and data models.
|
||||
- [03-program-design.md](docs/plans/inventory-collector/03-program-design.md) — Program design, signatures, and test plan.
|
||||
- [04-slices.md](docs/plans/inventory-collector/04-slices.md) — Vertical slice execution plan.
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
git clone https://gitea.wired.synology.me/soda64/inventory-collector.git
|
||||
cd inventory-collector
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### Quick Start
|
||||
```bash
|
||||
# Print Ansible YAML inventory to stdout
|
||||
./bin/inventory-collector
|
||||
|
||||
# Inspect discovered inventory in terminal table (dry run)
|
||||
./bin/inventory-collector --check
|
||||
|
||||
# Generate Ansible dynamic inventory JSON for CI/CD
|
||||
./bin/inventory-collector --list
|
||||
|
||||
# Synchronize both Ansible and linux-connector files simultaneously
|
||||
./bin/inventory-collector --sync
|
||||
```
|
||||
|
||||
### Static File Ingestion
|
||||
```bash
|
||||
./bin/inventory-collector --source static_hosts.ini -o inventory/hosts.yaml
|
||||
```
|
||||
|
||||
### Format Selection
|
||||
```bash
|
||||
# Export to XML
|
||||
./bin/inventory-collector --format xml -o fleet.xml
|
||||
|
||||
# Export to linux-connector
|
||||
./bin/inventory-collector --format linux-connector -o ~/.config/linux-connector/hosts.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration (`config.yaml`)
|
||||
|
||||
Store configuration in `~/.config/inventory-collector/config.yaml` or `./inventory-collector.yaml`:
|
||||
|
||||
```yaml
|
||||
sources:
|
||||
proxmox:
|
||||
enabled: true
|
||||
url: "${PROXMOX_URL}"
|
||||
token_id: "${PROXMOX_TOKEN_ID}"
|
||||
token_secret: "${PROXMOX_TOKEN_SECRET}"
|
||||
verify_ssl: false
|
||||
static_files:
|
||||
- path: "static_hosts.ini"
|
||||
required: false
|
||||
|
||||
defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- [User Guide](docs/user-guide.md) — Complete operational manual and examples.
|
||||
- [UNIX Manual Page](man/inventory-collector.1) — Section 1 manual page.
|
||||
- [Software Factory Plans](docs/plans/inventory-collector/) — Architecture, specifications, and design documents.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Bash completion script for inventory-collector
|
||||
|
||||
_inventory_collector_completion() {
|
||||
local cur prev opts formats
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
|
||||
opts="-o --output -f --format -s --source --check --dry-run --list --sync -c --config -V --version -h --help"
|
||||
formats="ansible-yaml ansible-json linux-connector yaml xml ini"
|
||||
|
||||
case "${prev}" in
|
||||
-f|--format)
|
||||
COMPREPLY=( $(compgen -W "${formats}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
-o|--output|-s|--source|-c|--config)
|
||||
COMPREPLY=( $(compgen -f -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ "${cur}" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
complete -F _inventory_collector_completion inventory-collector
|
||||
@@ -0,0 +1,27 @@
|
||||
#compdef inventory-collector
|
||||
|
||||
_inventory_collector() {
|
||||
local -a formats
|
||||
formats=(
|
||||
'ansible-yaml:Standard Ansible YAML inventory format'
|
||||
'ansible-json:Ansible dynamic inventory JSON with _meta.hostvars'
|
||||
'linux-connector:YAML schema formatted for linux-connector'
|
||||
'yaml:Clean generic YAML dictionary'
|
||||
'xml:Standard pretty-printed XML inventory'
|
||||
'ini:Ansible INI inventory format'
|
||||
)
|
||||
|
||||
_arguments \
|
||||
'(-o --output)'{-o,--output}'[Target output file path]:file:_files' \
|
||||
'(-f --format)'{-f,--format}'[Export format]:format:(ansible-yaml ansible-json linux-connector yaml xml ini)' \
|
||||
'*-s[Path to static inventory file (.ini or .yaml)]:file:_files' \
|
||||
'*--source[Path to static inventory file (.ini or .yaml)]:file:_files' \
|
||||
'(--check --dry-run)'{--check,--dry-run}'[Inspect inventory without writing any files]' \
|
||||
'--list[Ansible dynamic inventory mode: outputs JSON to stdout]' \
|
||||
'--sync[Synchronize inventory to both Ansible and linux-connector default paths]' \
|
||||
'(-c --config)'{-c,--config}'[Path to configuration file]:file:_files' \
|
||||
'(-V --version)'{-V,--version}'[Show program version and exit]' \
|
||||
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
||||
}
|
||||
|
||||
_inventory_collector "$@"
|
||||
@@ -11,7 +11,7 @@
|
||||
- [x] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution
|
||||
- [x] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings
|
||||
- [x] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag
|
||||
- [ ] Slice 6 — Configuration file (config.yaml), CLI check mode (--check), and documentation
|
||||
- [x] Slice 6 — Configuration file (config.yaml), CLI check mode (--check), and documentation
|
||||
|
||||
## Notes for a fresh session
|
||||
- Project: Universal homelab and fleet inventory collector and deduplicator.
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Inventory Collector User Guide
|
||||
|
||||
`inventory-collector` is a fast, dependency-light CLI utility that aggregates infrastructure hosts from multiple homelab sources (Proxmox VE REST API, static YAML and INI files), merges and deduplicates them in memory, and generates standardized inventory files for **Ansible** and **linux-connector**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Quick Start
|
||||
|
||||
### Basic Invocation
|
||||
Running `inventory-collector` without arguments outputs standard Ansible YAML inventory directly to stdout:
|
||||
|
||||
```bash
|
||||
inventory-collector
|
||||
```
|
||||
|
||||
### Dry-Run Inspection (`--check`)
|
||||
Preview all discovered hosts, groups, and deduplication sources in an ASCII table without modifying any files:
|
||||
|
||||
```bash
|
||||
inventory-collector --check
|
||||
```
|
||||
|
||||
Example output:
|
||||
```text
|
||||
[INFO] Discovered 12 hosts across 5 groups.
|
||||
NAME IP ADDRESS SOURCE GROUPS
|
||||
node0 192.168.0.101 proxmox:node proxmox_nodes
|
||||
k3s-master-0 192.168.5.70 hybrid k3s_cluster, k3s_master, proxmox_vms
|
||||
tool-server-1 192.168.5.61 proxmox:qemu proxmox_vms, tool_servers
|
||||
synology-nas 192.168.0.2 static:hosts.ini external, storage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. CLI Options Reference
|
||||
|
||||
| Flag | Argument | Description |
|
||||
|---|---|---|
|
||||
| `-o`, `--output` | `PATH` | Write inventory to destination file. Format is inferred from extension (`.xml`, `.ini`, `.json`, `.yaml`). |
|
||||
| `-f`, `--format` | `FORMAT` | Explicit output format: `ansible-yaml` (default), `ansible-json`, `linux-connector`, `yaml`, `xml`, `ini`. |
|
||||
| `-s`, `--source` | `PATH` | Path to static file (`.ini` or `.yaml`). Can be repeated multiple times. |
|
||||
| `--list` | *none* | Ansible Dynamic Inventory script mode (outputs JSON with `_meta.hostvars` to stdout). |
|
||||
| `--check`, `--dry-run` | *none* | Print summary table to stdout and exit. |
|
||||
| `--sync` | *none* | Update both Ansible (`inventory/hosts.yaml`) and `linux-connector` (`~/.config/linux-connector/hosts.yaml`) simultaneously. |
|
||||
| `-c`, `--config` | `PATH` | Path to configuration file. Default: `~/.config/inventory-collector/config.yaml`. |
|
||||
| `-V`, `--version` | *none* | Show version and exit. |
|
||||
| `-h`, `--help` | *none* | Show help message. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Configuration File (`config.yaml`)
|
||||
|
||||
Configuration can be stored in:
|
||||
- `./inventory-collector.yaml` (current directory)
|
||||
- `~/.config/inventory-collector/config.yaml` (user-level)
|
||||
- `/etc/inventory-collector/config.yaml` (system-level)
|
||||
|
||||
Environment variables `${VAR}` are automatically interpolated:
|
||||
|
||||
```yaml
|
||||
sources:
|
||||
proxmox:
|
||||
enabled: true
|
||||
url: "${PROXMOX_URL}"
|
||||
token_id: "${PROXMOX_TOKEN_ID}"
|
||||
token_secret: "${PROXMOX_TOKEN_SECRET}"
|
||||
verify_ssl: false
|
||||
timeout: 10
|
||||
static_files:
|
||||
- path: "~/.config/inventory-collector/static_hosts.ini"
|
||||
required: false
|
||||
|
||||
defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Integration Examples
|
||||
|
||||
### Ansible CLI
|
||||
Use generated static file:
|
||||
```bash
|
||||
ansible-playbook -i inventory/hosts.yaml site.yml
|
||||
```
|
||||
|
||||
Or execute `inventory-collector` directly as a dynamic inventory script:
|
||||
```bash
|
||||
ansible-playbook -i /usr/local/bin/inventory-collector site.yml
|
||||
```
|
||||
|
||||
### `linux-connector`
|
||||
Sync directly to `linux-connector`:
|
||||
```bash
|
||||
inventory-collector --format linux-connector -o ~/.config/linux-connector/hosts.yaml
|
||||
```
|
||||
Or run simultaneous sync:
|
||||
```bash
|
||||
inventory-collector --sync
|
||||
```
|
||||
|
||||
### Gitea Actions CI/CD Pipeline
|
||||
In `.gitea/workflows/run-ansible.yml`:
|
||||
```yaml
|
||||
- name: Generate Unified Inventory
|
||||
env:
|
||||
ANSIBLE_PROXMOX_URL: ${{ secrets.ANSIBLE_PROXMOX_URL }}
|
||||
ANSIBLE_PROXMOX_TOKEN_ID: ${{ secrets.ANSIBLE_PROXMOX_TOKEN_ID }}
|
||||
ANSIBLE_PROXMOX_TOKEN_SECRET: ${{ secrets.ANSIBLE_PROXMOX_TOKEN_SECRET }}
|
||||
run: |
|
||||
inventory-collector --source ansible/inventory/static_hosts.ini -o ansible/inventory/hosts.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Deduplication & Conflict Warnings
|
||||
|
||||
When the same machine is defined in multiple sources (e.g. in a static INI and dynamically discovered via Proxmox):
|
||||
- **Groups & Tags:** Merged into a unified set.
|
||||
- **Source:** Marked as `hybrid`.
|
||||
- **IP Discrepancy:** The Proxmox runtime IP takes precedence (`runtime_over_static`), and a warning is logged to `stderr`:
|
||||
```text
|
||||
[WARN] IP discrepancy for host 'tool-server-1': static specifies '192.168.5.61', Proxmox runtime reports '192.168.5.99'. Using runtime IP.
|
||||
```
|
||||
- **IP Collisions:** If two different hostnames share the same IP, both are preserved with a collision warning:
|
||||
```text
|
||||
[WARN] IP collision: hosts 'nas', 'synology-nas' share the same IP '192.168.0.2'. Keeping both entries.
|
||||
```
|
||||
- **Stdio Cleanliness:** Standard output (`stdout`) contains only clean inventory data (JSON, YAML, XML). All warnings and progress messages go to `stderr`.
|
||||
+32
-14
@@ -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)
|
||||
# 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)
|
||||
|
||||
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 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")
|
||||
# 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
|
||||
@@ -0,0 +1,63 @@
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from inventory_collector.cli import main
|
||||
|
||||
class TestCliIntegration(unittest.TestCase):
|
||||
def test_cli_dry_run_inspection(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"])
|
||||
self.assertEqual(code, 0)
|
||||
out = stdout_capture.getvalue()
|
||||
self.assertIn("NAME", out)
|
||||
self.assertIn("IP ADDRESS", out)
|
||||
self.assertIn("k3s-master-0", out)
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
sys.stderr = old_stderr
|
||||
|
||||
def test_cli_dynamic_json_list(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(["--list"])
|
||||
self.assertEqual(code, 0)
|
||||
parsed = json.loads(stdout_capture.getvalue())
|
||||
self.assertIn("_meta", parsed)
|
||||
self.assertIn("hostvars", parsed["_meta"])
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
sys.stderr = old_stderr
|
||||
|
||||
def test_cli_file_output_auto_xml(self):
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
target_xml = Path(tmpdir) / "output.xml"
|
||||
code = main(["-o", str(target_xml)])
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(target_xml.exists())
|
||||
content = target_xml.read_text(encoding="utf-8")
|
||||
self.assertIn("<inventory", content)
|
||||
self.assertIn("<host name=", content)
|
||||
|
||||
def test_cli_file_output_auto_ini(self):
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
target_ini = Path(tmpdir) / "hosts.ini"
|
||||
code = main(["-o", str(target_ini)])
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(target_ini.exists())
|
||||
content = target_ini.read_text(encoding="utf-8")
|
||||
self.assertIn("ansible_host=", content)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,51 @@
|
||||
import os
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
from inventory_collector.config import ConfigLoader, AppConfig
|
||||
|
||||
class TestConfigLoader(unittest.TestCase):
|
||||
def test_resolve_env_vars(self):
|
||||
os.environ["TEST_PVE_HOST"] = "pve.wired.intra"
|
||||
os.environ["TEST_SECRET"] = "secret123"
|
||||
|
||||
template = "https://${TEST_PVE_HOST}:8006/token=${TEST_SECRET}"
|
||||
resolved = ConfigLoader.resolve_env_vars(template)
|
||||
self.assertEqual(resolved, "https://pve.wired.intra:8006/token=secret123")
|
||||
|
||||
def test_load_config_file(self):
|
||||
os.environ["ENV_PVE_URL"] = "https://pve-01.test:8006"
|
||||
raw_config = """
|
||||
sources:
|
||||
proxmox:
|
||||
enabled: true
|
||||
url: "${ENV_PVE_URL}"
|
||||
token_id: "root@pam!test"
|
||||
token_secret: "uuid-secret"
|
||||
verify_ssl: false
|
||||
static_files:
|
||||
- path: "static_hosts.ini"
|
||||
required: false
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
"""
|
||||
with NamedTemporaryFile("w+", suffix=".yaml", delete=False) as f:
|
||||
f.write(raw_config)
|
||||
cfg_path = Path(f.name)
|
||||
|
||||
try:
|
||||
config = ConfigLoader.load(cfg_path)
|
||||
self.assertTrue(config.proxmox.enabled)
|
||||
self.assertEqual(config.proxmox.url, "https://pve-01.test:8006")
|
||||
self.assertEqual(config.proxmox.token_id, "root@pam!test")
|
||||
self.assertFalse(config.proxmox.verify_ssl)
|
||||
self.assertEqual(len(config.static_files), 1)
|
||||
self.assertEqual(config.static_files[0].path, Path("static_hosts.ini"))
|
||||
self.assertEqual(config.output_ansible, Path("inventory/hosts.yaml"))
|
||||
finally:
|
||||
cfg_path.unlink()
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user