Add awx_inventory_update j2 template

This commit is contained in:
2025-08-07 13:15:47 -05:00
parent 87d618f553
commit e7d4e86794

View File

@@ -0,0 +1,107 @@
#!/bin/bash
# AWX Inventory Update Script
# Generated on: {{ ansible_date_time.iso8601 }}
set -euo pipefail
# Configuration
LINODE_INVENTORY_SCRIPT="{{ linode_inventory_output_dir }}/linode_inventory.py"
INVENTORY_OUTPUT="{{ linode_inventory_output_dir }}/{{ linode_inventory_output_file }}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
log() {
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
warn() {
echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}
error() {
echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
exit 1
}
# Check prerequisites
check_prerequisites() {
log "Checking prerequisites..."
if [[ -z "${LINODE_API_TOKEN:-}" ]]; then
error "LINODE_API_TOKEN environment variable is not set"
fi
if ! command -v python3 >/dev/null 2>&1; then
error "python3 is not installed"
fi
if [[ ! -f "$LINODE_INVENTORY_SCRIPT" ]]; then
error "Inventory script not found: $LINODE_INVENTORY_SCRIPT"
fi
log "Prerequisites check passed"
}
# Update inventory
update_inventory() {
log "Updating Linode inventory..."
if ! python3 "$LINODE_INVENTORY_SCRIPT" --list > "$INVENTORY_OUTPUT.tmp"; then
error "Failed to generate inventory"
fi
# Validate JSON
if ! python3 -m json.tool "$INVENTORY_OUTPUT.tmp" >/dev/null 2>&1; then
error "Generated inventory is not valid JSON"
fi
# Move to final location
mv "$INVENTORY_OUTPUT.tmp" "$INVENTORY_OUTPUT"
log "Inventory updated successfully: $INVENTORY_OUTPUT"
}
# Display summary
display_summary() {
if [[ -f "$INVENTORY_OUTPUT" ]]; then
local host_count
host_count=$(python3 -c "import json; data=json.load(open('$INVENTORY_OUTPUT')); print(len(data.get('_meta', {}).get('hostvars', {})))")
local group_count
group_count=$(python3 -c "import json; data=json.load(open('$INVENTORY_OUTPUT')); print(len([k for k in data.keys() if k != '_meta']))")
log "Inventory Summary:"
log " Hosts discovered: $host_count"
log " Groups created: $group_count"
log " Output file: $INVENTORY_OUTPUT"
# List hosts
log "Discovered hosts:"
python3 -c "
import json
data = json.load(open('$INVENTORY_OUTPUT'))
for hostname, vars in data.get('_meta', {}).get('hostvars', {}).items():
print(f' - {hostname} ({vars.get(\"ansible_host\", \"no-ip\")}) - {vars.get(\"linode_region\", \"unknown\")} - {vars.get(\"linode_status\", \"unknown\")}')
"
fi
}
# Main execution
main() {
log "Starting AWX Linode inventory update"
check_prerequisites
update_inventory
display_summary
log "Inventory update completed successfully"
}
# Run if executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi