#!/usr/bin/env bash set -euo pipefail # k3d_route_fix.sh # Purpose: # - Ensure k3d node containers SNAT pod traffic to reach LAN services (e.g., AD DC) # - Adds a targeted MASQUERADE rule for the pod CIDR -> AD DC IP SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck disable=SC1090 source "$SCRIPT_DIR/prole_cfg.sh" log() { printf '%s\n' "$*"; } err() { printf '%s\n' "$*" >&2; } cluster_name="${K3D_CLUSTER_NAME:-knoe-dev-cluster}" ad_dc_ip="${AD_DC_IP:-${KDC_ANSIBLE_DETECTED:-${KDC_AUTO_DETECTED:-}}}" if [[ -z "$ad_dc_ip" ]]; then err "ERROR: AD DC IP not found (set AD_DC_IP)." exit 1 fi pod_cidr="" pod_cidr_raw=$(kubectl get nodes -o jsonpath='{range .items[*]}{.spec.podCIDR}{"\n"}{end}' 2>/dev/null || true) if [[ -n "$pod_cidr_raw" ]]; then # Use first podCIDR; for k3d this is usually a /24 within a shared /16. first_cidr=$(printf '%s' "$pod_cidr_raw" | head -n 1 | tr -d '\r') if [[ "$first_cidr" == */* ]]; then pod_cidr="$first_cidr" fi fi if [[ -z "$pod_cidr" ]]; then err "ERROR: Unable to determine pod CIDR from the cluster." exit 1 fi # Collapse /24 to /16 when possible to cover all nodes. if [[ "$pod_cidr" =~ ^([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/24$ ]]; then pod_cidr="${BASH_REMATCH[1]}.0.0/16" fi log "Applying k3d route fix for cluster '${cluster_name}'..." log "Pod CIDR: ${pod_cidr}" log "AD DC IP: ${ad_dc_ip}" nodes=$(docker ps --format '{{.Names}}' | awk -v c="k3d-${cluster_name}-" '$0 ~ "^"c && $0 !~ /serverlb/ && $0 !~ /-tools$/ {print $0}') if [[ -z "$nodes" ]]; then err "ERROR: No k3d node containers found for cluster ${cluster_name}." exit 1 fi for node in $nodes; do log "Updating NAT rules on ${node} ..." if ! docker exec "$node" sh -c "command -v iptables >/dev/null 2>&1"; then echo "WARN: iptables not found in ${node}; skipping NAT rule." >&2 continue fi docker exec "$node" sh -c "iptables -t nat -C POSTROUTING -s ${pod_cidr} -d ${ad_dc_ip}/32 -j MASQUERADE >/dev/null 2>&1 || \ iptables -t nat -I POSTROUTING 1 -s ${pod_cidr} -d ${ad_dc_ip}/32 -j MASQUERADE" done log "k3d route fix applied."