homelab-codex-ws/scripts/lib/inventory.sh

46 lines
1.5 KiB
Bash

#!/usr/bin/env bash
# inventory.sh - Host and service discovery
load_inventory() {
local host=$1
local service_override=$2
log "INFO" "Loading inventory for host: $host"
if [[ ! -d "${REPO_PATH}/hosts/${host}" ]]; then
log "ERROR" "Host directory not found: ${REPO_PATH}/hosts/${host}"
return 1
fi
if [[ -n "$service_override" ]]; then
SERVICES=("$service_override")
else
if [[ -f "${REPO_PATH}/hosts/${host}/services.txt" ]]; then
# Read services from text file, ignoring comments and empty lines
mapfile -t SERVICES < <(grep -v '^\s*#' "${REPO_PATH}/hosts/${host}/services.txt" | grep -v '^\s*$')
elif [[ -f "${REPO_PATH}/hosts/${host}/services.yaml" ]]; then
# Use python for reliable YAML parsing
SERVICES=($(python3 -c "
import yaml, sys
try:
with open('${REPO_PATH}/hosts/${host}/services.yaml', 'r') as f:
data = yaml.safe_load(f)
if data and 'services' in data:
if isinstance(data['services'], dict):
print(' '.join(data['services'].keys()))
elif isinstance(data['services'], list):
print(' '.join(data['services']))
except Exception as e:
print(f'Error parsing YAML: {e}', file=sys.stderr)
sys.exit(1)
"))
else
log "WARN" "No services found for $host"
SERVICES=()
fi
fi
log "INFO" "Services to process: ${SERVICES[*]}"
}
export -f load_inventory