Files
SnarfCode/scripts/setup_keepalived.sh
2026-06-11 10:13:57 -04:00

114 lines
3.0 KiB
Bash

#!/bin/bash
#
# Keepalived Setup Script for 5-Node Docker Cluster
# VIP: 140.44.4.70
# Nodes: 140.44.4.71 - 140.44.4.75
#
# Usage: sudo bash setup_keepalived.sh
#
set -euo pipefail
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
if [ "$(id -u)" -ne 0 ]; then
log "ERROR: This script must be run as root (use sudo)."
exit 1
fi
VIP="140.44.4.70"
VIP_CIDR="24"
ROUTER_ID="70"
AUTH_PASS="DockerHA123!"
log "Detecting primary network interface and IP..."
# Find interface with default route to the gateway (140.44.4.1)
IFACE=$(ip route | awk '/default/ {print $5}' | head -n1)
if [ -z "$IFACE" ]; then
log "ERROR: Could not detect default network interface."
exit 1
fi
# Find IP of that interface
MY_IP=$(ip -4 addr show dev "$IFACE" | awk '/inet / {print $2}' | cut -d/ -f1)
if [ -z "$MY_IP" ]; then
log "ERROR: Could not detect IP address for interface $IFACE."
exit 1
fi
log "Detected IP: $MY_IP on interface: $IFACE"
# Validate IP and determine priority
case "$MY_IP" in
140.44.4.71) PRIORITY=150; STATE="MASTER" ;;
140.44.4.72) PRIORITY=140; STATE="BACKUP" ;;
140.44.4.73) PRIORITY=130; STATE="BACKUP" ;;
140.44.4.74) PRIORITY=120; STATE="BACKUP" ;;
140.44.4.75) PRIORITY=110; STATE="BACKUP" ;;
*)
log "ERROR: This IP ($MY_IP) is not part of the expected cluster (140.44.4.71-75)."
exit 1
;;
esac
log "Installing keepalived..."
if command -v apt-get &> /dev/null; then
apt-get update -y && apt-get install -y keepalived
elif command -v dnf &> /dev/null; then
dnf install -y keepalived
elif command -v yum &> /dev/null; then
yum install -y keepalived
else
log "ERROR: Unsupported package manager. Please install keepalived manually."
exit 1
fi
log "Configuring keepalived (State: $STATE, Priority: $PRIORITY)..."
# Create a health check script for Docker
mkdir -p /etc/keepalived/scripts
cat << 'EOF' > /etc/keepalived/scripts/check_docker.sh
#!/bin/bash
# Returns 0 if docker is active, 1 if it is stopped/crashed
systemctl is-active --quiet docker
EOF
chmod +x /etc/keepalived/scripts/check_docker.sh
# Backup existing config if any
[ -f /etc/keepalived/keepalived.conf ] && mv /etc/keepalived/keepalived.conf "/etc/keepalived/keepalived.conf.bak.$(date +%s)"
# Create new config
cat << EOF > /etc/keepalived/keepalived.conf
vrrp_script chk_docker {
script "/etc/keepalived/scripts/check_docker.sh"
interval 2
weight -20
}
vrrp_instance VI_1 {
state $STATE
interface $IFACE
virtual_router_id $ROUTER_ID
priority $PRIORITY
advert_int 1
authentication {
auth_type PASS
auth_pass $AUTH_PASS
}
virtual_ipaddress {
$VIP/$VIP_CIDR dev $IFACE
}
track_script {
chk_docker
}
}
EOF
log "Restarting and enabling keepalived service..."
systemctl enable keepalived
systemctl restart keepalived
log "=== Keepalived setup complete on $MY_IP ==="
log "Check status with: systemctl status keepalived"
log "Virtual IP $VIP will be active on the node with the highest priority."