Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d562c09e0c | ||
|
|
c116834be9 | ||
|
|
1dbbb1ce56 | ||
|
|
62710d8bb7 |
No files matched your search
@@ -8,7 +8,10 @@ Universal homelab and fleet inventory collector and deduplicator for **Ansible**
|
||||
|
||||
- **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.
|
||||
- **4-Tier IP Resolution:** QEMU Guest Agent $\rightarrow$ PVE hardware config (`ipconfig0`) $\rightarrow$ Static definitions $\rightarrow$ Local DNS resolution with wildcard NXDOMAIN collision protection.
|
||||
- **Filtering & Selective Querying:** Filter inventory dynamically by tag (`-t`), group/category (`-g`), or source provider (`--source-type {proxmox,static,k3s}`).
|
||||
- **Mathematical IP & Name Sorting:** Sort hosts by name or IP (`--sort {name,ip}`, `-r/--reverse`). IP sorting accurately evaluates IPv4 octets (32-bit integer) and IPv6 addresses, handling CIDR prefixes (`/24`) and ports (`:22`).
|
||||
- **Clean YAML (No Anchors):** Generates clean, human-readable YAML without YAML anchors or aliases (`&id`/`*id`).
|
||||
- **Multi-Format Exporters:**
|
||||
- `ansible-yaml`: Native Ansible YAML inventory (`all.children`).
|
||||
- `ansible-json`: Executable Ansible Dynamic Inventory script format (`--list` with `_meta.hostvars`).
|
||||
@@ -16,9 +19,9 @@ Universal homelab and fleet inventory collector and deduplicator for **Ansible**
|
||||
- `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`).
|
||||
- **Simultaneous Target Sync (`--sync`):** Synchronizes both Ansible and `linux-connector` inventories with one command, with customizable destination paths (`--ansible-dest`, `--lc-dest`) and `~` home directory expansion.
|
||||
- **Zero-Secrets Policy:** Credentials read from environment variables (`PROXMOX_*`, `ANSIBLE_PROXMOX_*`) or configuration files with variable interpolation and automatic `.env` loading.
|
||||
- **Lean Runtime:** Pure Python 3 standard library with optional `PyYAML` acceleration.
|
||||
|
||||
---
|
||||
|
||||
@@ -32,13 +35,13 @@ sudo dnf install -y inventory-collector
|
||||
|
||||
### From Debian / Ubuntu (.deb)
|
||||
```bash
|
||||
sudo dpkg -i inventory-collector_1.0.0_all.deb
|
||||
sudo dpkg -i inventory-collector_1.1.3_all.deb
|
||||
```
|
||||
|
||||
### Standalone Tarball Installer
|
||||
```bash
|
||||
tar -xzf inventory-collector-1.0.0.tar.gz
|
||||
cd inventory-collector-1.0.0
|
||||
tar -xzf inventory-collector-1.1.3.tar.gz
|
||||
cd inventory-collector-1.1.3
|
||||
sudo ./install.sh
|
||||
```
|
||||
|
||||
@@ -56,37 +59,59 @@ pip install -r requirements.txt
|
||||
### Quick Start
|
||||
```bash
|
||||
# Print Ansible YAML inventory to stdout
|
||||
./bin/inventory-collector
|
||||
inventory-collector
|
||||
|
||||
# Inspect discovered inventory in terminal table (dry run)
|
||||
./bin/inventory-collector --check
|
||||
inventory-collector --check
|
||||
|
||||
# Generate Ansible dynamic inventory JSON for CI/CD
|
||||
./bin/inventory-collector --list
|
||||
inventory-collector --list
|
||||
|
||||
# Synchronize both Ansible and linux-connector files simultaneously
|
||||
./bin/inventory-collector --sync
|
||||
inventory-collector --sync
|
||||
```
|
||||
|
||||
### Static File Ingestion
|
||||
### Sorting & Filtering
|
||||
```bash
|
||||
./bin/inventory-collector --source static_hosts.ini -o inventory/hosts.yaml
|
||||
# Sort hosts mathematically by IP address (numerical 32-bit order)
|
||||
inventory-collector --check --sort ip
|
||||
|
||||
# Filter only Proxmox VMs tagged with 'k3s'
|
||||
inventory-collector --check --source-type proxmox -t k3s
|
||||
|
||||
# Filter by group and sort by IP in reverse order
|
||||
inventory-collector -g storage --sort ip -r
|
||||
|
||||
# Export filtered inventory to Ansible YAML
|
||||
inventory-collector -t production --sort ip -o inventory/production.yaml
|
||||
```
|
||||
|
||||
### Synchronization & Custom Destinations
|
||||
```bash
|
||||
# Sync with explicit destination paths
|
||||
inventory-collector --sync --ansible-dest ~/.config/inventory-collector/hosts.yaml --lc-dest ~/.config/linux-connector/hosts.yaml
|
||||
|
||||
# Sync with custom Ansible path using short flag -o
|
||||
inventory-collector --sync -o /etc/ansible/hosts.yaml --sort ip
|
||||
```
|
||||
|
||||
### Format Selection
|
||||
```bash
|
||||
# Export to XML
|
||||
./bin/inventory-collector --format xml -o fleet.xml
|
||||
inventory-collector --format xml --sort ip -o fleet.xml
|
||||
|
||||
# Export to INI
|
||||
inventory-collector --format ini --sort ip -o hosts.ini
|
||||
|
||||
# Export to linux-connector
|
||||
./bin/inventory-collector --format linux-connector -o ~/.config/linux-connector/hosts.yaml
|
||||
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`:
|
||||
Store configuration in `~/.config/inventory-collector/config.yaml`, `/etc/inventory-collector/config.yaml`, or `./inventory-collector.yaml`:
|
||||
|
||||
```yaml
|
||||
sources:
|
||||
@@ -96,17 +121,22 @@ sources:
|
||||
token_id: "${PROXMOX_TOKEN_ID}"
|
||||
token_secret: "${PROXMOX_TOKEN_SECRET}"
|
||||
verify_ssl: false
|
||||
timeout: 10
|
||||
static_files:
|
||||
- path: "static_hosts.ini"
|
||||
- path: "~/.config/inventory-collector/static_hosts.ini"
|
||||
required: false
|
||||
|
||||
defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
sort_by: "ip" # Default sorting: "name" or "ip"
|
||||
sort_reverse: false # Set true to reverse sort order by default
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
# In --sync mode, destinations define where unified inventories are written.
|
||||
# Supports '~' home expansion or absolute paths:
|
||||
ansible: "~/.config/inventory-collector/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ _inventory_collector_completion() {
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
|
||||
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"
|
||||
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 --sort --sort-by -r --reverse --ansible-dest --lc-dest -V --version -h --help"
|
||||
formats="ansible-yaml ansible-json linux-connector yaml xml ini"
|
||||
|
||||
case "${prev}" in
|
||||
@@ -18,7 +18,11 @@ _inventory_collector_completion() {
|
||||
COMPREPLY=( $(compgen -W "proxmox static file plik k3s" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
-o|--output|-s|--source|-c|--config)
|
||||
--sort|--sort-by)
|
||||
COMPREPLY=( $(compgen -W "name ip" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
-o|--output|-s|--source|-c|--config|--ansible-dest|--lc-dest)
|
||||
COMPREPLY=( $(compgen -f -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
|
||||
@@ -25,6 +25,10 @@ _inventory_collector() {
|
||||
'(-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)' \
|
||||
'(--sort --sort-by)'{--sort,--sort-by}'[Sort hosts by name or ip]:sort:(name ip)' \
|
||||
'(-r --reverse)'{-r,--reverse}'[Reverse sort order]' \
|
||||
'--ansible-dest[Destination path for Ansible inventory in --sync mode]:file:_files' \
|
||||
'--lc-dest[Destination path for linux-connector inventory in --sync mode]:file:_files' \
|
||||
'(-V --version)'{-V,--version}'[Show program version and exit]' \
|
||||
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
||||
}
|
||||
|
||||
+6
-1
@@ -20,7 +20,12 @@ defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
sort_by: "name" # Default sorting: "name" or "ip"
|
||||
sort_reverse: false # Set true to reverse sorting by default
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
# In --sync mode, destinations define where unified inventories are written.
|
||||
# Paths support '~' expansion or absolute paths (e.g. ~/.config/inventory-collector/hosts.yaml).
|
||||
# Relative paths (like inventory/hosts.yaml) are relative to current working directory.
|
||||
ansible: "~/.config/inventory-collector/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
@@ -25,3 +25,16 @@
|
||||
- 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.
|
||||
- Release v1.1.1:
|
||||
- Added host sorting by name and numerical IPv4 octets (--sort {name,ip}, -r/--reverse).
|
||||
- Preserved host order in all 6 exporters (Ansible YAML, JSON, Linux-Connector, Generic YAML, XML, INI).
|
||||
- Added destination override flags for --sync mode (--ansible-dest, --lc-dest, -o).
|
||||
- Added ~ expansion support for config destinations and CLI paths.
|
||||
- Release v1.1.2:
|
||||
- Hardened IP sorting with Python standard `ipaddress` module for 32-bit/128-bit numerical sorting.
|
||||
- Handled CIDR prefixes (`/24`) and port numbers (`:22`) cleanly in IP sort key.
|
||||
- Added configuration file support for `sort_by` and `sort_reverse` under `defaults:`.
|
||||
- Release v1.1.3:
|
||||
- Fully synchronized all documentation (README, User Guide, manual page, completions).
|
||||
- Production release with hardened sorting and full documentation parity.
|
||||
|
||||
+67
-10
@@ -39,19 +39,66 @@ synology-nas 192.168.0.2 static:hosts.ini external, storage
|
||||
| `-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. |
|
||||
| `--list` | *none* | Ansible Dynamic Inventory script mode (outputs JSON with `_meta.hostvars` to stdout). Stderr is quieted. |
|
||||
| `--check`, `--dry-run` | *none* | Print summary table to stdout and exit without modifying any files. |
|
||||
| `--sync` | *none* | Update both Ansible (`destinations.ansible`) and `linux-connector` (`destinations.linux_connector`) simultaneously. |
|
||||
| `-t`, `--tag`, `--filter-tag` | `TAG` | Filter inventory hosts by tag (case-insensitive, e.g. `hypervisor`, `k3s`). |
|
||||
| `-g`, `--group`, `--filter-group` | `GROUP` | Filter inventory hosts by group or category name (e.g. `proxmox_vms`, `storage`). |
|
||||
| `--source-type`, `--origin` | `SOURCE` | Filter hosts by source provider (`proxmox`, `static`, `file`, `k3s`). |
|
||||
| `--sort`, `--sort-by` | `FIELD` | Sort hosts by `name` or `ip` (default: `name`, or config setting). Evaluates 32-bit/128-bit numerical IP order. |
|
||||
| `-r`, `--reverse` | *none* | Reverse the sort order. |
|
||||
| `--ansible-dest` | `PATH` | Target output path for Ansible inventory in `--sync` mode (overrides config). |
|
||||
| `--lc-dest` | `PATH` | Target output path for linux-connector inventory in `--sync mode` (overrides config). |
|
||||
| `-q`, `--quiet` | *none* | Silence all informational and warning log messages on stderr. |
|
||||
| `-v`, `--verbose` | *none* | Enable verbose logging on stderr (forces output even in `--list` mode). |
|
||||
| `-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`)
|
||||
## 3. Filtering & Sorting
|
||||
|
||||
### Filtering Hosts
|
||||
You can filter hosts in check mode (`--check`), sync mode (`--sync`), or when exporting to any format:
|
||||
|
||||
```bash
|
||||
# Filter by tag:
|
||||
inventory-collector --check -t hypervisor
|
||||
|
||||
# Filter by group / category:
|
||||
inventory-collector --check -g proxmox_vms
|
||||
|
||||
# Filter by source provider (e.g. only hosts discovered via Proxmox):
|
||||
inventory-collector --check --source-type proxmox
|
||||
|
||||
# Combine filters:
|
||||
inventory-collector --check --source-type proxmox -t k3s -g k3s_cluster
|
||||
```
|
||||
|
||||
### Sorting Hosts
|
||||
Hosts can be sorted either by hostname or by IP address:
|
||||
|
||||
```bash
|
||||
# Sort alphabetically by hostname (default):
|
||||
inventory-collector --check --sort name
|
||||
|
||||
# Sort numerically by IP address (IPv4 32-bit octets / IPv6):
|
||||
inventory-collector --check --sort ip
|
||||
|
||||
# Reverse sort order:
|
||||
inventory-collector --check --sort ip -r
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> IP sorting accurately evaluates full IPv4 octets (`(192, 168, 0, 101) < (192, 168, 5, 51)` because $0 < 5$). CIDR prefixes (`/24`) and ports (`:22`) are automatically stripped before numerical comparison.
|
||||
|
||||
---
|
||||
|
||||
## 4. Configuration File (`config.yaml`)
|
||||
|
||||
Configuration can be stored in:
|
||||
- `./inventory-collector.yaml` (current directory)
|
||||
- `./inventory-collector.yaml` (current working directory)
|
||||
- `~/.config/inventory-collector/config.yaml` (user-level)
|
||||
- `/etc/inventory-collector/config.yaml` (system-level)
|
||||
|
||||
@@ -74,15 +121,19 @@ defaults:
|
||||
ssh_user: "lain"
|
||||
ssh_port: 22
|
||||
conflict_policy: "runtime_over_static"
|
||||
sort_by: "ip" # Default sorting: "name" or "ip"
|
||||
sort_reverse: false # Set true to reverse sort order by default
|
||||
|
||||
destinations:
|
||||
ansible: "inventory/hosts.yaml"
|
||||
# In --sync mode, destinations define where unified inventories are written.
|
||||
# Supports '~' home expansion or absolute paths:
|
||||
ansible: "~/.config/inventory-collector/hosts.yaml"
|
||||
linux_connector: "~/.config/linux-connector/hosts.yaml"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Integration Examples
|
||||
## 5. Integration Examples
|
||||
|
||||
### Ansible CLI
|
||||
Use generated static file:
|
||||
@@ -100,9 +151,15 @@ Sync directly to `linux-connector`:
|
||||
```bash
|
||||
inventory-collector --format linux-connector -o ~/.config/linux-connector/hosts.yaml
|
||||
```
|
||||
Or run simultaneous sync:
|
||||
|
||||
### Simultaneous Sync (`--sync`)
|
||||
Update both Ansible and `linux-connector` simultaneously:
|
||||
```bash
|
||||
# Uses destinations configured in config.yaml:
|
||||
inventory-collector --sync
|
||||
|
||||
# Or override destinations ad-hoc from CLI:
|
||||
inventory-collector --sync --ansible-dest /etc/ansible/hosts.yaml --lc-dest ~/.config/linux-connector/hosts.yaml --sort ip
|
||||
```
|
||||
|
||||
### Gitea Actions CI/CD Pipeline
|
||||
@@ -114,12 +171,12 @@ In `.gitea/workflows/run-ansible.yml`:
|
||||
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
|
||||
inventory-collector --source ansible/inventory/static_hosts.ini --sort ip -o ansible/inventory/hosts.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Deduplication & Conflict Warnings
|
||||
## 6. 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.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Universal homelab and fleet inventory collector and deduplicator."""
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__version__ = "1.1.3"
|
||||
|
||||
_yaml_warning_emitted = False
|
||||
|
||||
|
||||
@@ -116,6 +116,29 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
dest="filter_source",
|
||||
help="Filter hosts by source provider (e.g. 'proxmox', 'static', 'file', 'k3s')."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--sort", "--sort-by",
|
||||
dest="sort_by",
|
||||
choices=["name", "ip"],
|
||||
default=None,
|
||||
help="Sort hosts by 'name' or 'ip' (default: name, or config default)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-r", "--reverse",
|
||||
action="store_true",
|
||||
default=None,
|
||||
help="Reverse the sort order."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ansible-dest",
|
||||
type=Path,
|
||||
help="Target output path for Ansible inventory in --sync mode (overrides config)."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--lc-dest",
|
||||
type=Path,
|
||||
help="Target output path for linux-connector inventory in --sync mode (overrides config)."
|
||||
)
|
||||
return parser
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
@@ -205,6 +228,11 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
source=args.filter_source
|
||||
)
|
||||
|
||||
# 4c. Sort inventory by name or IP
|
||||
sort_by = args.sort_by or app_config.sort_by or "name"
|
||||
sort_reverse = args.reverse if args.reverse is not None else app_config.sort_reverse
|
||||
inv = inv.sort(sort_by=sort_by, reverse=sort_reverse)
|
||||
|
||||
# 5. Inspection / Dry-run Mode
|
||||
if args.dry_run:
|
||||
filter_desc = []
|
||||
@@ -231,8 +259,17 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
# 7. Simultaneous Synchronization Mode (--sync)
|
||||
if args.sync:
|
||||
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()
|
||||
ansible_dest = (
|
||||
args.ansible_dest
|
||||
or (args.output if args.output else None)
|
||||
or app_config.output_ansible
|
||||
or Path("inventory/hosts.yaml")
|
||||
).expanduser()
|
||||
lc_dest = (
|
||||
args.lc_dest
|
||||
or app_config.output_linux_connector
|
||||
or Path("~/.config/linux-connector/hosts.yaml")
|
||||
).expanduser()
|
||||
|
||||
AnsibleYamlExporter().write_to_file(inv, ansible_dest)
|
||||
if not is_quiet:
|
||||
|
||||
@@ -31,6 +31,8 @@ class AppConfig:
|
||||
output_linux_connector: Optional[Path] = None
|
||||
output_yaml: Optional[Path] = None
|
||||
output_xml: Optional[Path] = None
|
||||
sort_by: str = "name"
|
||||
sort_reverse: bool = False
|
||||
|
||||
class ConfigLoader:
|
||||
"""Loads configuration with environment variable interpolation."""
|
||||
@@ -197,17 +199,21 @@ class ConfigLoader:
|
||||
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)
|
||||
if "sort_by" in defaults:
|
||||
config.sort_by = str(defaults["sort_by"])
|
||||
if "sort_reverse" in defaults:
|
||||
config.sort_reverse = bool(defaults["sort_reverse"])
|
||||
|
||||
# Parse destinations
|
||||
destinations = data.get("destinations", {})
|
||||
if destinations:
|
||||
if "ansible" in destinations:
|
||||
config.output_ansible = Path(destinations["ansible"])
|
||||
config.output_ansible = Path(destinations["ansible"]).expanduser()
|
||||
if "linux_connector" in destinations:
|
||||
config.output_linux_connector = Path(destinations["linux_connector"])
|
||||
config.output_linux_connector = Path(destinations["linux_connector"]).expanduser()
|
||||
if "yaml" in destinations:
|
||||
config.output_yaml = Path(destinations["yaml"])
|
||||
config.output_yaml = Path(destinations["yaml"]).expanduser()
|
||||
if "xml" in destinations:
|
||||
config.output_xml = Path(destinations["xml"])
|
||||
config.output_xml = Path(destinations["xml"]).expanduser()
|
||||
|
||||
return config
|
||||
@@ -17,7 +17,7 @@ class AnsibleJsonExporter(BaseExporter):
|
||||
}
|
||||
|
||||
# Populate hostvars
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
for name, host in data.hosts.items():
|
||||
hvars: Dict[str, Any] = {
|
||||
"ansible_host": host.ansible_host,
|
||||
"ansible_user": host.ansible_user,
|
||||
@@ -26,7 +26,8 @@ class AnsibleJsonExporter(BaseExporter):
|
||||
if host.ansible_ssh_private_key_file:
|
||||
hvars["ansible_ssh_private_key_file"] = host.ansible_ssh_private_key_file
|
||||
if host.tags:
|
||||
hvars["tags"] = host.tags
|
||||
tags_list = host.tags
|
||||
hvars["tags"] = tags_list
|
||||
for k, v in host.variables.items():
|
||||
hvars[k] = v
|
||||
payload["_meta"]["hostvars"][name] = hvars
|
||||
@@ -34,7 +35,7 @@ class AnsibleJsonExporter(BaseExporter):
|
||||
# Populate groups
|
||||
for grp_name, host_names in sorted(data.groups.items()):
|
||||
payload[grp_name] = {
|
||||
"hosts": sorted(host_names)
|
||||
"hosts": list(host_names)
|
||||
}
|
||||
|
||||
return json.dumps(payload, indent=2) + "\n"
|
||||
@@ -17,7 +17,7 @@ class AnsibleYamlExporter(BaseExporter):
|
||||
grouped_hosts = set()
|
||||
for group_name, host_names in sorted(data.groups.items()):
|
||||
group_dict: Dict[str, Any] = {"hosts": {}}
|
||||
for name in sorted(host_names):
|
||||
for name in host_names:
|
||||
host = data.get_host(name)
|
||||
if not host:
|
||||
continue
|
||||
@@ -37,10 +37,10 @@ class AnsibleYamlExporter(BaseExporter):
|
||||
structure["all"]["children"][group_name] = group_dict
|
||||
|
||||
# Ungrouped hosts placed directly under all.hosts
|
||||
ungrouped = {name: host for name, host in data.hosts.items() if name not in grouped_hosts}
|
||||
ungrouped = [host for name, host in data.hosts.items() if name not in grouped_hosts]
|
||||
if ungrouped:
|
||||
structure["all"]["hosts"] = {}
|
||||
for name, host in sorted(ungrouped.items()):
|
||||
for host in ungrouped:
|
||||
host_vars = {
|
||||
"ansible_host": host.ansible_host,
|
||||
"ansible_user": host.ansible_user,
|
||||
@@ -50,7 +50,7 @@ class AnsibleYamlExporter(BaseExporter):
|
||||
host_vars["tags"] = host.tags
|
||||
for k, v in host.variables.items():
|
||||
host_vars[k] = v
|
||||
structure["all"]["hosts"][name] = host_vars
|
||||
structure["all"]["hosts"][host.name] = host_vars
|
||||
|
||||
return structure
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ class GenericYamlExporter(BaseExporter):
|
||||
|
||||
def _build_structure(self, data: InventoryData) -> Dict[str, Any]:
|
||||
hosts_list: List[Dict[str, Any]] = []
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
for name, host in data.hosts.items():
|
||||
h_dict: Dict[str, Any] = {
|
||||
"name": host.name,
|
||||
"ip": host.ansible_host,
|
||||
@@ -22,7 +22,7 @@ class GenericYamlExporter(BaseExporter):
|
||||
|
||||
groups_dict: Dict[str, List[str]] = {}
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
groups_dict[grp_name] = sorted(members)
|
||||
groups_dict[grp_name] = list(members)
|
||||
|
||||
return {
|
||||
"hosts": hosts_list,
|
||||
|
||||
@@ -11,7 +11,7 @@ class IniExporter(BaseExporter):
|
||||
grouped_hosts = set()
|
||||
for grp_name, host_names in sorted(data.groups.items()):
|
||||
lines.append(f"[{grp_name}]")
|
||||
for h_name in sorted(host_names):
|
||||
for h_name in host_names:
|
||||
host = data.get_host(h_name)
|
||||
if not host:
|
||||
continue
|
||||
@@ -29,7 +29,7 @@ class IniExporter(BaseExporter):
|
||||
lines.append("")
|
||||
|
||||
# Ungrouped hosts
|
||||
ungrouped = [h for name, h in sorted(data.hosts.items()) if name not in grouped_hosts]
|
||||
ungrouped = [h for name, h in data.hosts.items() if name not in grouped_hosts]
|
||||
if ungrouped:
|
||||
lines.append("[ungrouped]")
|
||||
for host in ungrouped:
|
||||
|
||||
@@ -8,7 +8,7 @@ class LinuxConnectorExporter(BaseExporter):
|
||||
|
||||
def _build_structure(self, data: InventoryData) -> Dict[str, Any]:
|
||||
hosts_list: List[Dict[str, Any]] = []
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
for name, host in data.hosts.items():
|
||||
h_dict: Dict[str, Any] = {
|
||||
"name": host.name,
|
||||
"hostname": host.ansible_host,
|
||||
@@ -25,7 +25,7 @@ class LinuxConnectorExporter(BaseExporter):
|
||||
|
||||
groups_dict: Dict[str, List[str]] = {}
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
groups_dict[grp_name] = sorted(members)
|
||||
groups_dict[grp_name] = list(members)
|
||||
|
||||
return {
|
||||
"hosts": hosts_list,
|
||||
|
||||
@@ -12,7 +12,7 @@ class XmlExporter(BaseExporter):
|
||||
root.set("generated_at", datetime.now(timezone.utc).isoformat())
|
||||
|
||||
hosts_elem = ET.SubElement(root, "hosts")
|
||||
for name, host in sorted(data.hosts.items()):
|
||||
for name, host in data.hosts.items():
|
||||
h_elem = ET.SubElement(hosts_elem, "host")
|
||||
h_elem.set("name", host.name)
|
||||
h_elem.set("ip", host.ansible_host)
|
||||
@@ -43,7 +43,7 @@ class XmlExporter(BaseExporter):
|
||||
for grp_name, members in sorted(data.groups.items()):
|
||||
g_elem = ET.SubElement(groups_elem, "group")
|
||||
g_elem.set("name", grp_name)
|
||||
for m in sorted(members):
|
||||
for m in members:
|
||||
m_elem = ET.SubElement(g_elem, "member")
|
||||
m_elem.text = m
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ipaddress
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Any
|
||||
|
||||
@@ -56,3 +57,34 @@ class InventoryData:
|
||||
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
|
||||
@@ -1,4 +1,4 @@
|
||||
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.1.0" "User Commands"
|
||||
.TH INVENTORY-COLLECTOR 1 "October 2026" "inventory-collector 1.1.3" "User Commands"
|
||||
.SH NAME
|
||||
inventory-collector \- Universal homelab and fleet inventory collector and deduplicator
|
||||
.SH SYNOPSIS
|
||||
@@ -33,6 +33,18 @@ Filter inventory hosts by group or category name (e.g. \fIproxmox_vms\fR, \fIsto
|
||||
.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 \-\-sort ", " \-\-sort\-by " \fIFIELD\fR"
|
||||
Sort inventory hosts by \fIname\fR or \fIip\fR (default: \fIname\fR). IP sorting accurately evaluates IPv4 octets in mathematical order.
|
||||
.TP
|
||||
.BR \-r ", " \-\-reverse
|
||||
Reverse the current sort order.
|
||||
.TP
|
||||
.BR \-\-ansible\-dest " \fIPATH\fR"
|
||||
Target output path for Ansible inventory in \fB\-\-sync\fR mode (overrides configuration file).
|
||||
.TP
|
||||
.BR \-\-lc\-dest " \fIPATH\fR"
|
||||
Target output path for linux-connector inventory in \fB\-\-sync\fR mode (overrides configuration file).
|
||||
.TP
|
||||
.BR \-q ", " \-\-quiet
|
||||
Silence all informational and warning log messages on stderr.
|
||||
.TP
|
||||
|
||||
@@ -296,8 +296,7 @@ class PackageBuilder:
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
# Find created .rpm and copy to dist/
|
||||
rpms = list(rpms_dir.glob("**/*.rpm"))
|
||||
rpms = [r for r in rpms_dir.glob(f"**/*{self.version}*.rpm") if not r.name.endswith(".src.rpm")]
|
||||
if rpms:
|
||||
for rpm in rpms:
|
||||
shutil.copy2(str(rpm), str(self.output_dir / rpm.name))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: inventory-collector
|
||||
Version: 1.1.0
|
||||
Version: 1.1.3
|
||||
Release: 1%{?dist}
|
||||
Summary: Universal homelab and fleet inventory collector and deduplicator
|
||||
|
||||
@@ -66,6 +66,21 @@ fi
|
||||
%doc %{_datadir}/doc/inventory-collector
|
||||
|
||||
%changelog
|
||||
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.3-1
|
||||
- Synchronize comprehensive documentation across README, User Guide, and manual page.
|
||||
- Harden numerical IP sorting against CIDR masks, port numbers, and IPv6.
|
||||
- Full configuration file integration for default sorting and destination paths.
|
||||
|
||||
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.2-1
|
||||
- Use Python standard ipaddress module for robust numerical 32-bit/128-bit IP sorting.
|
||||
- Handle CIDR notation (/24) and port numbers (:22) gracefully in IP sorting.
|
||||
- Support default sort configuration (sort_by, sort_reverse) in config.yaml.
|
||||
|
||||
* Sat Oct 03 2026 Mateusz Stomski <zbytatencyjny@gmail.com> - 1.1.1-1
|
||||
- Add host sorting by name and IP (--sort {name,ip}, -r/--reverse).
|
||||
- Add destination override flags in --sync mode (--ansible-dest, --lc-dest, -o).
|
||||
- Support ~ expansion in config destinations and CLI paths.
|
||||
|
||||
* 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.
|
||||
|
||||
@@ -113,5 +113,38 @@ class TestCliIntegration(unittest.TestCase):
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
|
||||
def test_cli_sort_by_ip(self):
|
||||
stdout_capture = StringIO()
|
||||
old_stdout = sys.stdout
|
||||
try:
|
||||
sys.stdout = stdout_capture
|
||||
code = main(["--check", "-q", "--sort", "ip"])
|
||||
self.assertEqual(code, 0)
|
||||
out = stdout_capture.getvalue()
|
||||
# node0 (192.168.0.101) must appear before k3s-master-0 (192.168.5.70)
|
||||
pos_node0 = out.find("node0")
|
||||
pos_k3s = out.find("k3s-master-0")
|
||||
self.assertNotEqual(pos_node0, -1)
|
||||
self.assertNotEqual(pos_k3s, -1)
|
||||
self.assertLess(pos_node0, pos_k3s)
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
|
||||
def test_cli_sync_destination_overrides(self):
|
||||
with TemporaryDirectory() as tmpdir:
|
||||
ansible_file = Path(tmpdir) / "custom_ansible.yaml"
|
||||
lc_file = Path(tmpdir) / "custom_lc.yaml"
|
||||
|
||||
code = main([
|
||||
"--sync", "-q",
|
||||
"--ansible-dest", str(ansible_file),
|
||||
"--lc-dest", str(lc_file)
|
||||
])
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(ansible_file.exists())
|
||||
self.assertTrue(lc_file.exists())
|
||||
self.assertIn("all:", ansible_file.read_text(encoding="utf-8"))
|
||||
self.assertIn("hosts:", lc_file.read_text(encoding="utf-8"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -63,5 +63,22 @@ destinations:
|
||||
finally:
|
||||
env_file.unlink()
|
||||
|
||||
def test_load_config_sort_defaults(self):
|
||||
content = """
|
||||
defaults:
|
||||
sort_by: "ip"
|
||||
sort_reverse: true
|
||||
"""
|
||||
with NamedTemporaryFile("w+", suffix=".yaml", delete=False) as f:
|
||||
f.write(content)
|
||||
cfg_path = Path(f.name)
|
||||
|
||||
try:
|
||||
config = ConfigLoader.load(cfg_path)
|
||||
self.assertEqual(config.sort_by, "ip")
|
||||
self.assertTrue(config.sort_reverse)
|
||||
finally:
|
||||
cfg_path.unlink()
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -71,5 +71,59 @@ class TestDeduplicationEngine(unittest.TestCase):
|
||||
merged = inv.get_host("node0")
|
||||
self.assertEqual(merged.ansible_user, "root")
|
||||
|
||||
def test_inventory_sort_by_name(self):
|
||||
from inventory_collector.models import InventoryData
|
||||
inv = InventoryData()
|
||||
inv.add_host(HostRecord(name="zebra", ansible_host="10.0.0.1"))
|
||||
inv.add_host(HostRecord(name="alpha", ansible_host="10.0.0.2"))
|
||||
inv.add_host(HostRecord(name="beta", ansible_host="10.0.0.3"))
|
||||
|
||||
sorted_inv = inv.sort(sort_by="name")
|
||||
self.assertEqual(list(sorted_inv.hosts.keys()), ["alpha", "beta", "zebra"])
|
||||
|
||||
rev_inv = inv.sort(sort_by="name", reverse=True)
|
||||
self.assertEqual(list(rev_inv.hosts.keys()), ["zebra", "beta", "alpha"])
|
||||
|
||||
def test_inventory_sort_by_ip(self):
|
||||
from inventory_collector.models import InventoryData
|
||||
inv = InventoryData()
|
||||
inv.add_host(HostRecord(name="host-101", ansible_host="192.168.0.101"))
|
||||
inv.add_host(HostRecord(name="host-2", ansible_host="192.168.0.2"))
|
||||
inv.add_host(HostRecord(name="host-20", ansible_host="192.168.0.20"))
|
||||
inv.add_host(HostRecord(name="host-no-ip", ansible_host=""))
|
||||
|
||||
# In string sorting, "192.168.0.101" < "192.168.0.2".
|
||||
# But numerical octet sorting correctly places .2 before .20 before .101!
|
||||
sorted_inv = inv.sort(sort_by="ip")
|
||||
self.assertEqual(list(sorted_inv.hosts.keys()), ["host-2", "host-20", "host-101", "host-no-ip"])
|
||||
|
||||
rev_inv = inv.sort(sort_by="ip", reverse=True)
|
||||
self.assertEqual(list(rev_inv.hosts.keys()), ["host-no-ip", "host-101", "host-20", "host-2"])
|
||||
|
||||
def test_inventory_sort_by_ip_robustness(self):
|
||||
from inventory_collector.models import InventoryData
|
||||
inv = InventoryData()
|
||||
inv.add_host(HostRecord(name="node0", ansible_host="192.168.0.101"))
|
||||
inv.add_host(HostRecord(name="node0-cidr", ansible_host="192.168.0.2/24"))
|
||||
inv.add_host(HostRecord(name="node0-port", ansible_host="192.168.0.101:2222"))
|
||||
inv.add_host(HostRecord(name="alma-crash", ansible_host="192.168.5.51"))
|
||||
inv.add_host(HostRecord(name="rhcsa-111", ansible_host="192.168.5.111"))
|
||||
inv.add_host(HostRecord(name="ipv6-host", ansible_host="fe80::1"))
|
||||
inv.add_host(HostRecord(name="named-host", ansible_host="nas.wired.intra"))
|
||||
inv.add_host(HostRecord(name="empty-host", ansible_host=""))
|
||||
|
||||
sorted_inv = inv.sort(sort_by="ip")
|
||||
expected_order = [
|
||||
"node0-cidr", # 192.168.0.2
|
||||
"node0", # 192.168.0.101
|
||||
"node0-port", # 192.168.0.101:2222 (tie broken by name)
|
||||
"alma-crash", # 192.168.5.51 (51 < 111)
|
||||
"rhcsa-111", # 192.168.5.111
|
||||
"ipv6-host", # fe80::1 (IPv6 after IPv4)
|
||||
"named-host", # nas.wired.intra (hostname after IP)
|
||||
"empty-host", # "" (empty IP at end)
|
||||
]
|
||||
self.assertEqual(list(sorted_inv.hosts.keys()), expected_order)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -33,13 +33,13 @@ class TestPackaging(unittest.TestCase):
|
||||
|
||||
def test_get_version(self):
|
||||
version = get_version(self.source_root)
|
||||
self.assertEqual(version, "1.1.0")
|
||||
self.assertEqual(version, "1.1.3")
|
||||
|
||||
def test_build_tarball(self):
|
||||
builder = PackageBuilder(
|
||||
source_root=self.source_root,
|
||||
output_dir=self.output_dir,
|
||||
version="1.1.0",
|
||||
version="1.1.3",
|
||||
)
|
||||
tar_path = builder.build_tarball()
|
||||
self.assertTrue(tar_path.exists())
|
||||
@@ -48,16 +48,16 @@ class TestPackaging(unittest.TestCase):
|
||||
# Verify tar contents
|
||||
with tarfile.open(str(tar_path), "r:gz") as tar:
|
||||
names = tar.getnames()
|
||||
self.assertIn("inventory-collector-1.1.0/bin/inventory-collector", names)
|
||||
self.assertIn("inventory-collector-1.1.0/inventory_collector/__init__.py", names)
|
||||
self.assertIn("inventory-collector-1.1.0/install.sh", names)
|
||||
self.assertIn("inventory-collector-1.1.0/packaging/install.sh", names)
|
||||
self.assertIn("inventory-collector-1.1.3/bin/inventory-collector", names)
|
||||
self.assertIn("inventory-collector-1.1.3/inventory_collector/__init__.py", names)
|
||||
self.assertIn("inventory-collector-1.1.3/install.sh", names)
|
||||
self.assertIn("inventory-collector-1.1.3/packaging/install.sh", names)
|
||||
|
||||
def test_build_deb(self):
|
||||
builder = PackageBuilder(
|
||||
source_root=self.source_root,
|
||||
output_dir=self.output_dir,
|
||||
version="1.1.0",
|
||||
version="1.1.3",
|
||||
)
|
||||
deb_path = builder.build_deb()
|
||||
self.assertTrue(deb_path.exists())
|
||||
|
||||
Reference in new issue
Block a user