81 lines
2.8 KiB
Bash
81 lines
2.8 KiB
Bash
#!/bin/bash
|
|
|
|
# Grafana Auto-Configuration Script for Prometheus Datasource
|
|
# This script ensures Grafana is properly configured to connect to Prometheus
|
|
|
|
set -e
|
|
|
|
# Default values
|
|
GRAFANA_URL="http://localhost:3000"
|
|
GRAFANA_USER="admin"
|
|
GRAFANA_PASSWORD="${GRAFANA_ADMIN_PASSWORD:-admin}"
|
|
PROMETHEUS_URL="http://prometheus:9090"
|
|
PROMETHEUS_USER="${PROMETHEUS_USERNAME:-prometheus_user}"
|
|
PROMETHEUS_PASSWORD="${PROMETHEUS_PASSWORD:-prometheus_password}"
|
|
|
|
# Wait for Grafana to be ready
|
|
echo "Waiting for Grafana to be ready..."
|
|
until curl -s "${GRAFANA_URL}/api/health" | grep -q '"database":"ok"'; do
|
|
sleep 5
|
|
done
|
|
echo "Grafana is ready!"
|
|
|
|
# Check if Prometheus datasource already exists
|
|
echo "Checking for existing Prometheus datasource..."
|
|
DATASOURCES=$(curl -s -u "${GRAFANA_USER}:${GRAFANA_PASSWORD}" "${GRAFANA_URL}/api/datasources")
|
|
|
|
if echo "$DATASOURCES" | grep -q '"name":"Prometheus"'; then
|
|
echo "Prometheus datasource already exists. Updating configuration..."
|
|
|
|
# Get the datasource ID
|
|
DATASOURCE_ID=$(echo "$DATASOURCES" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
|
|
|
|
# Update the datasource
|
|
curl -s -X PUT "${GRAFANA_URL}/api/datasources/${DATASOURCE_ID}" \
|
|
-u "${GRAFANA_USER}:${GRAFANA_PASSWORD}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "{
|
|
\"name\": \"Prometheus\",
|
|
\"type\": \"prometheus\",
|
|
\"url\": \"${PROMETHEUS_URL}\",
|
|
\"access\": \"proxy\",
|
|
\"basicAuth\": true,
|
|
\"basicAuthUser\": \"${PROMETHEUS_USER}\",
|
|
\"basicAuthPassword\": \"${PROMETHEUS_PASSWORD}\",
|
|
\"isDefault\": true
|
|
}"
|
|
|
|
echo "Prometheus datasource updated successfully!"
|
|
else
|
|
echo "Creating Prometheus datasource..."
|
|
|
|
# Create the datasource
|
|
curl -s -X POST "${GRAFANA_URL}/api/datasources" \
|
|
-u "${GRAFANA_USER}:${GRAFANA_PASSWORD}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "{
|
|
\"name\": \"Prometheus\",
|
|
\"type\": \"prometheus\",
|
|
\"url\": \"${PROMETHEUS_URL}\",
|
|
\"access\": \"proxy\",
|
|
\"basicAuth\": true,
|
|
\"basicAuthUser\": \"${PROMETHEUS_USER}\",
|
|
\"basicAuthPassword\": \"${PROMETHEUS_PASSWORD}\",
|
|
\"isDefault\": true
|
|
}"
|
|
|
|
echo "Prometheus datasource created successfully!"
|
|
fi
|
|
|
|
# Test the datasource connection
|
|
echo "Testing Prometheus datasource connection..."
|
|
TEST_RESULT=$(curl -s -u "${GRAFANA_USER}:${GRAFANA_PASSWORD}" "${GRAFANA_URL}/api/datasources/1/health")
|
|
|
|
if echo "$TEST_RESULT" | grep -q '"status":"OK"'; then
|
|
echo "✅ Prometheus datasource connection test passed!"
|
|
else
|
|
echo "❌ Prometheus datasource connection test failed:"
|
|
echo "$TEST_RESULT"
|
|
fi
|
|
|
|
echo "Grafana configuration completed!" |