Files
Homelabv4/scripts/import-unifi-dashboards.sh
2026-03-09 20:21:35 -05:00

105 lines
3.1 KiB
Bash
Executable File

#!/bin/bash
# Import Unifi dashboards into Grafana via API
# This script downloads the dashboards from GitHub and imports them properly
set -euo pipefail
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}=== Importing Unifi Dashboards to Grafana ===${NC}"
echo ""
# Port forward to Grafana
echo "Setting up port-forward to Grafana..."
kubectl -n grafana port-forward svc/grafana 3000:80 >/dev/null 2>&1 &
PF_PID=$!
sleep 3
# Grafana API credentials (using default admin/admin for now)
GRAFANA_URL="http://localhost:3000"
API_KEY=""
# Function to cleanup
cleanup() {
echo ""
echo "Cleaning up port-forward..."
kill $PF_PID 2>/dev/null || true
}
trap cleanup EXIT
# Get admin password from Kubernetes secret or use default
ADMIN_PASS=$(kubectl -n grafana get secret grafana -o jsonpath='{.data.admin-password}' 2>/dev/null | base64 -d || echo "admin")
# Dashboards to import
DASHBOARDS=("unifi-access-points" "unifi-clients" "unifi-gateway" "unifi-pdu" "unifi-sites" "unifi-switches")
for dashboard in "${DASHBOARDS[@]}"; do
echo -e "${YELLOW}Importing ${dashboard}...${NC}"
# Download dashboard
curl -sL "https://raw.githubusercontent.com/timothystewart6/unpoller-unifi/main/grafana/provisioning/dashboards/${dashboard}.json" -o "/tmp/${dashboard}.json"
# Fix datasource references and wrap for import
python3 << PYEOF
import json
with open('/tmp/${dashboard}.json', 'r') as f:
data = json.load(f)
# Remove template fields
data.pop('__inputs', None)
data.pop('__requires', None)
data.pop('id', None)
# Fix datasource references
def fix_datasource(obj):
if isinstance(obj, dict):
for key, value in obj.items():
if key == 'datasource':
if isinstance(value, str) and ('DS_PROMETHEUS' in value or value == ''):
obj[key] = {'type': 'prometheus', 'uid': 'Prometheus'}
elif isinstance(value, dict) and value.get('type') == 'prometheus':
obj[key] = {'type': 'prometheus', 'uid': 'Prometheus'}
else:
fix_datasource(value)
elif isinstance(obj, list):
for item in obj:
fix_datasource(item)
fix_datasource(data)
# Wrap for import API
import_data = {
"dashboard": data,
"overwrite": True,
"inputs": [],
"folderId": 0
}
with open('/tmp/${dashboard}-import.json', 'w') as f:
json.dump(import_data, f)
PYEOF
# Import via API
response=$(curl -s -X POST \
-H "Content-Type: application/json" \
-u "admin:${ADMIN_PASS}" \
-d @/tmp/${dashboard}-import.json \
"${GRAFANA_URL}/api/dashboards/db")
if echo "$response" | grep -q '"status":"success"'; then
echo -e "${GREEN}✓ Successfully imported ${dashboard}${NC}"
else
echo -e "${YELLOW}⚠ Failed to import ${dashboard}: $response${NC}"
fi
rm -f "/tmp/${dashboard}.json" "/tmp/${dashboard}-import.json"
done
echo ""
echo -e "${GREEN}✓ Dashboard import complete!${NC}"
echo ""
echo "Visit https://grafana.kube.huskypup.net and search for 'Unifi' to find your dashboards."